pythondictionary

Python list of tuples to nested dict


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


Solution

  • You can do it in one statement

    rows = [('a','x1',1),('a','x2',5),('b','x1',1)]
    result = dict()
    for key1, key2, value in rows:
      result.setdefault(key1, {}).update({key2: value})