将列表中的列表转换为字典

gol*_*ian 1 python dictionary

我得到了一个这样的列表:

[['a','b','1','2']['c','d','3','4']]
Run Code Online (Sandbox Code Playgroud)

我想将此列表转换为字典,如下所示:

{
    ('a','b'):('1','2'),
    ('c','d'):('3','4')
}
Run Code Online (Sandbox Code Playgroud)

例如, ('a', 'b') & ('c','d') 表示键, ('1','2') &('3','4') 表示值

所以我使用了这样的代码

new_dict = {}
for i, k in enumerate(li[0:2]):
    new_dict[k] =[x1[i] for x1 in li[2:]]
print(new_dict)
Run Code Online (Sandbox Code Playgroud)

,但它导致了不可散列的类型错误“列表”

我尝试了其他几种方法,但效果不佳.. 有什么办法可以解决它吗?

azr*_*zro 5

你不能有list作为关键,但tuple有可能。此外,您不需要在列表上切片,而是在子列表上切片。

您需要前 2 个值sublist[:2]作为键,相应的值是索引 2 中的子列表sublist[2:]

new_dict = {}
for sublist in li:
    new_dict[tuple(sublist[:2])] = tuple(sublist[2:])

print(new_dict)  # {('a', 'b'): ('1', '2'), ('c', 'd'): ('3', '4')}
Run Code Online (Sandbox Code Playgroud)

与字典理解相同

new_dict = {tuple(sublist[:2]): tuple(sublist[2:]) for sublist in li}
print(new_dict)  # {('a', 'b'): ('1', '2'), ('c', 'd'): ('3', '4')}
Run Code Online (Sandbox Code Playgroud)