将嵌套列表转换成嵌套字典[python]

我有这个清单:

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

我想创建这个字典:

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

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

有人可以帮我吗?我尝试了多种方法,但没有成功。

评论
Lily
Lily

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}}
点赞
评论
lipsum
lipsum

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
点赞
评论