问题描述
我有一个这样的列表:
[['a','b','1','2']['c','d','3','4']]
我想将此列表转换为字典,如下所示:
and I want to convert this list to dictionary something looks like this:
{
('a','b'):('1','2'),
('c','d'):('3','4')
}
例如,('a','b')& ('c','d')表示键
,而('1','2')&('3','4')表示值
for example, ('a', 'b') & ('c','d') for keyand ('1','2') &('3','4') for value
所以我用了类似这样的代码
so I used code something like this
new_dict = {}
for i, k in enumerate(li[0:2]):
new_dict[k] =[x1[i] for x1 in li[2:]]
print(new_dict)
,但是它导致了无法散列的类型错误列表
,but it caused unhashable type error 'list'
我尝试了其他几种方法,但是效果不好。.
有什么办法可以解决它?
I tried several other way, but it didn't work well..Is there any way that I can fix it?
推荐答案
您不能将 list
作为键,但可以使用 tuple
。另外,您不需要在列表上切片,而在子列表上。
You can't have list
as key, but tuple
is possible. Also you don't need to slice on your list, but on the sublist.
您需要前两个值 sublist [:2]
作为键,对应的值是索引2 sublist [2:]
You need the 2 first values sublist[:2]
as key and the corresponding values is the sublist from index 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')}
与dict理解相同
new_dict = {tuple(sublist[:2]): tuple(sublist[2:]) for sublist in li}
print(new_dict) # {('a', 'b'): ('1', '2'), ('c', 'd'): ('3', '4')}
这篇关于将列表中的列表转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!