[Python] Python list of tuples to nested dict

Discussão em 'Python' iniciado por Stack, Fevereiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    I have a data structure as follows:

    [(a,x1,1),(a,x2,5),(b,x1,1) ...]


    and i want to turn it into a nested dictionary of the form

    {a:{x1:1, x2:5}, b:{x1:1}...}


    I tried

    dictdata = {}
    for row in rows:
    ean = row[1].encode('ascii','ignore')
    period = str(row[0])
    value = row[2]
    dictdata[ean]={} # init sub dictionary
    dictdata[ean][period] = value


    but every time I do dictdata[ean]={}, the contents get erased, so this will not work. If I do not initialise the sub-dictionary, I also cannot get it to work.

    Any help appreciated

    Continue reading...

Compartilhe esta Página