问题
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