Converting nested list into nested dictionary

这一生的挚爱 提交于 2020-06-23 14:15:45

问题


I have this list:

list1 = [['X1',2],['X2',4],['Y1',2],['Y2',4]]

and I want to create this dict:

dict1 = {'X': {'1':2},{'2':4},'Y':{'1':2},{'2':4}}

so that I can use dict1['X']['1'] and this outputs '2'

Can someone help me out? I've tried multiple approaches but without any success.


回答1:


You can use collections.defaultdict:

>>> from collections import defaultdict
>>> list1 = [['X1',2],['X2',4],['Y1',2],['Y2',4]]
>>> d = defaultdict(dict)
>>> for (c,i), n in list1:
...     d[c][i] = n
... 
>>> d
defaultdict(<class 'dict'>, {'X': {'1': 2, '2': 4}, 'Y': {'1': 2, '2': 4}})
>>> d['X']['1']
2



回答2:


dict1 = {'X': {'1':2},{'2':4},'Y':{'1':2},{'2':4}} is syntax-wise illegal.

Assuming you meant {'X': {'1': 2, '2': 4}, 'Y': {'1': 2, '2': 4}}

In [1]: list1 = [['X1',2],['X2',4],['Y1',2],['Y2',4]]

In [2]: unique_letters = {k[0] for k, _ in list1}

In [3]: unique_letters
Out[3]: {'X', 'Y'}

In [4]: dict1 = {k: {} for k in unique_letters}

In [5]: for k, v in list1:
    ...:     dict1[k[0]][k[1]] = v
    ...:

In [6]: dict1
Out[6]: {'X': {'1': 2, '2': 4}, 'Y': {'1': 2, '2': 4}}


来源:https://stackoverflow.com/questions/61852275/converting-nested-list-into-nested-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!