[英]Convert a list of lists to a dictionary
How do I create a dictionary from a Python list of lists so that the first row are the keys and the rest are a list under that key?如何从 Python 列表列表创建字典,以便第一行是键,其余是该键下的列表?
x = [['A', 'B', 'C'],
[100, 90, 80],
[88, 99, 111],
[45, 56, 67],
[59, 61, 67],
[73, 79, 83],
[89, 97, 101]]
Currently with a dict comprehension I am getting:目前,我得到了 dict 理解:
{i[0]: i[1:] for i in x}
{'A': ['B', 'C'],
100: [90, 80],
88: [99, 111],
45: [56, 67],
59: [61, 67],
73: [79, 83],
89: [97, 101]}
The desired result is:期望的结果是:
{
"A": [100, 88, 45, 59, 73, 89],
"B": [90, 99, 56, 61, 79, 97],
"C": [80, 111, 67, 83, 101],
}
How do I slice the dictionary comprehension the correct way?如何以正确的方式对字典理解进行切片?
You have zip
as an option:您可以选择
zip
:
wanted = {a[0]: list(a[1:]) for a in zip(*x)}
Or if you're familiar with unpacking:或者,如果您熟悉拆包:
wanted = {k: v for k, *v in zip(*x)}
For loop and list comprehension:对于循环和列表理解:
x = [['A', 'B', 'C'],
[100, 90, 80],
[88, 99, 111],
[45, 56, 67],
[59, 61, 67],
[73, 79, 83],
[89, 97, 101]]
dict1={}
for i,k in enumerate( x[0]):
dict1[k]=[x1[i] for x1 in x[1:]]
print(dict1)
#{'A': [100, 88, 45, 59, 73, 89], 'B': [90, 99, 56, 61, 79, 97], 'C': [80, 111, 67, 67, 83, 101]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.