我有此列表:
list1 = [['X1',2],['X2',4],['Y1',2],['Y2',4]]
我想创建这个字典:
dict1 = {'X': {'1':2},{'2':4},'Y':{'1':2},{'2':4}}
这样我就可以使用dict1['X']['1']
并输出'2'
有人可以帮我吗?我尝试了多种方法,但没有成功。
答案 0 :(得分:3)
您可以使用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
答案 1 :(得分:0)
dict1 = {'X': {'1':2},{'2':4},'Y':{'1':2},{'2':4}}
在语法上是非法的。
假设您的意思是{'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}}