[英]How do I create a dictionary with lists as values?
How can I get this output:我怎样才能得到这个 output:
{'Test 1': ['100', '88', '45', '59', '73', '89'], 'Test 2': ['90', '99', '56', '61', '79', '97'], 'Test 3': ['80', '111', '67', '67', '83', '101']}
with this data有了这个数据
grades = [
['Students', 'Test 1', 'Test 2', 'Test 3'],
['Tomas', '100', '90', '80'],
['Marcos', '88', '99', '111'],
['Flavia', '45', '56', '67'],
['Ramon', '59', '61', '67'],
['Ursula', '73', '79', '83'],
['Federico', '89', '97', '101']
]
The first element (row) of grades
contains all the keys you want to use. grades
的第一个元素(行)包含您要使用的所有键。 Every other row contains the values of the keys in every column.每隔一行包含每一列中键的值。 You can use
zip
with unpacking like so: zip(grades[0], *grades[1:])
to obtain an iterator that gives a tuple containing the key as the first element, and the corresponding column from every other row in the remaining elements.您可以使用
zip
进行解包,如下所示: zip(grades[0], *grades[1:])
获得一个迭代器,该迭代器给出一个包含键作为第一个元素的元组,以及剩余的每隔一行的对应列元素。 Then, you can unpack this using k, *v in zip(...)
to get the key in k
, and a list of the values in the column in v
.然后,您可以使用
k, *v in zip(...)
以获取k
中的键,以及v
中列中的值列表。
Then, you can use a dictionary comprehension to create a dictionary out of the result of the zip
operation.然后,您可以使用字典推导根据
zip
操作的结果创建字典。 k:v
is keys and values for the dictionary, for k in grades[0]
so each iteration will give k one element from grades[0]
, then *v
is a full vertical column. k:v
是字典的键和值,对于k in grades[0]
所以每次迭代都会给 k 一个来自grades[0]
的元素,然后*v
是一个完整的垂直列。
{k: v for k, *v in zip(grades[0], *grades[1:])}
# Result:
{'Students': ['Tomas', 'Marcos', 'Flavia', 'Ramon', 'Ursula', 'Federico'],
'Test 1': ['100', '88', '45', '59', '73', '89'],
'Test 2': ['90', '99', '56', '61', '79', '97'],
'Test 3': ['80', '111', '67', '67', '83', '101']}
dictt ={}
for n,i in enumerate(grades[0][1:],start=1):
dictt[i] = [x[n] for x in grades[1:]]
print(dictt)
>>> {'Test 1': ['100', '88', '45', '59', '73', '89'], 'Test 2': ['90', '99', '56', '61', '79', '97'], 'Test 3': ['80', '111', '67', '67', '83', '101']}
start = 1
omits from adding the labels to the dictionary values start = 1
省略将标签添加到字典值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.