[英]Converting list in list to dictionary
I got a list like this:我得到了一个这样的列表:
[['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')
}
for example, ('a', 'b') & ('c','d') for key and ('1','2') &('3','4') for value例如, ('a', 'b') & ('c','d') 表示键, ('1','2') &('3','4') 表示值
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?我尝试了其他几种方法,但效果不佳.. 有什么办法可以解决它吗?
You can't have list
as key, but tuple
is possible.您不能将
list
作为键,但tuple
是可能的。 Also you don't need to slice on your list, but on the sublist.此外,您不需要在列表上切片,而是在子列表上切片。
You need the 2 first values sublist[:2]
as key and the corresponding values is the sublist from index 2 sublist[2:]
您需要 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')}
The same with dict comprehension与字典理解相同
new_dict = {tuple(sublist[:2]): tuple(sublist[2:]) for sublist in li}
print(new_dict) # {('a', 'b'): ('1', '2'), ('c', 'd'): ('3', '4')}
I would use list
-comprehension following way:我会使用
list
-comprehension 以下方式:
lst = [['a','b','1','2']['c','d','3','4']]
dct = dict([(tuple(i[:2]),tuple(i[2:])) for i in lst])
print(dct)
or alternatively dict
-comprehension:或者
dict
理解:
dct = {tuple(i[:2]):tuple(i[2:]) for i in lst}
Output:输出:
{('a', 'b'): ('1', '2'), ('c', 'd'): ('3', '4')}
Note that list
slicing produce list
s, which are mutable and can not be used as dict
keys, so I use tuple
to convert these to immutable tuples.请注意,
list
切片会生成list
s,它们是可变的,不能用作dict
键,因此我使用tuple
将它们转换为不可变的元组。
li = [['a','b','1','2'],['c','d','3','4']]
new_dict = {}
for item in li:
new_dict[(item[0], item[1])] = (item[2], item[3])
You can do it with dict comprehension:您可以使用 dict 理解来做到这一点:
li = [
['a', 'b', '1', '2'],
['c', 'd', '3', '4'],
]
new_dict = {(i[0], i[1]): (i[2], i[3]) for i in li}
print(new_dict)
# result
{('a', 'b'): ('1', '2'), ('c', 'd'): ('3', '4')}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.