简体   繁体   English

将列表列表转换为词典字典

[英]Convert list of lists to dictionary of dictionaries

I have a Python list which holds key/values 我有一个包含键/值的Python列表

[ [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? 这样做的优雅的Python方法是什么? Thanks. 谢谢。

You can use collections.defaultdict() : 您可以使用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: 最好的方法可能是将dict用作工厂的defaultdict:

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: defaultdict可以像普通字典一样使用,但是之后您也可以将其转换为普通字典:

>>> 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'}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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