简体   繁体   中英

Convert list of lists to dictionary of dictionaries

I have a Python list which holds key/values

[ [001, 'A', '100'], [001, 'B', '94'], [002, 'A', '87'], [002, 'B', '85'] ]

but the first 2 columns make a unique key. I want to convert the list into a dictionary, where multiple values per key would be aggregated into a dictionary of dictionaries for easy value lookups

{'001': {'A':'100','B':'94'}, '002': {'A':'87','B':'85'} }

What would be the elegant Python way of doing this? Thanks.

You can use collections.defaultdict() :

In [54]: lst = [ ['001', 'A', '100'], ['001', 'B', '94'], ['002', 'A', '87'], ['002', 'B', '85'] ]

In [55]: from collections import defaultdict

In [56]: d = defaultdict(dict)

In [57]: for i, j, k in lst:
   ....:     d[i].update({j:k})
   ....:     

In [58]: d
Out[58]: defaultdict(<class 'dict'>, {'001': {'A': '100', 'B': '94'}, '002': {'A': '87', 'B': '85'}})

Probably the best way is a defaultdict using a dict as factory:

from collections import defaultdict

dictofdicts = defaultdict(dict)

start = [ ['001', 'A', '100'], ['001', 'B', '94'], ['002', 'A', '87'], ['002', 'B', '85'] ]

for outerkey, innerkey, value in start:
    dictofdicts[outerkey][innerkey] = value

and this gives you the solution you wanted:

>>> dictofdicts
defaultdict(dict,
            {'001': {'A': '100', 'B': '94'}, '002': {'A': '87', 'B': '85'}})

The defaultdict can be used like a normal dictionary but you can also convert it to a plain dictionary afterwards:

>>> dict(dictofdicts)
{'001': {'A': '100', 'B': '94'}, '002': {'A': '87', 'B': '85'}}

In a dictionary comprehension:

>>> l = [ ['001', 'A', '100'], ['001', 'B', '94'], ['002', 'A', '87'], ['002', 'B', '85'] ]
>>> {l[i][0]:{k:v for (k, v) in zip(l[i][1:], l[i+1][1:])} for i in range(0, len(l), 2)}
{'002': {'A': 'B', '87': '85'}, '001': {'100': '94', 'A': 'B'}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM