[英]How can I add a list of values to a dictionary where the first element in the list belongs to the first key and so on...?
I have a dictionary which has predefined keys:我有一本具有预定义键的字典:
{1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None}
and a list with numeric values:和一个带有数值的列表:
[0, 10, 20, 30, 40, 50, 60, 100]
I want to add these values from the list to the dictionary so that it will look like this:我想将列表中的这些值添加到字典中,以便它看起来像这样:
{1: 0, 2: 10, 3: 20, 4: 30, 5: 40, 6: 50, 7: 60, 8: 100}
How can I add every item from the list to the next key of my dictionary?如何将列表中的每个项目添加到字典的下一个键?
You directly use zip
on the dict and the list of values, tha make pairs, then ues dict
to make mappings from pairs您直接在 dict 和值列表上使用
zip
进行配对,然后使用dict
从对进行映射
d = {1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None}
v = [0, 10, 20, 30, 40, 50, 60, 100]
res = dict(zip(d, v))
print(res) # {1: 0, 2: 10, 3: 20, 4: 30, 5: 40, 6: 50, 7: 60, 8: 100}
You could find strange to passe the whole dict d
to zip
but iterating over th dict is same as iterating over its key in fact, the following can have more sense but it does the same您可能会发现将整个字典
d
传递给zip
很奇怪,但迭代字典实际上与迭代其键相同,以下内容可能更有意义,但它的作用相同
dict(zip(d.keys(), v))
Below is more dynamic solution where you dont have prepare half populated dict下面是更动态的解决方案,您没有准备半人口的字典
a_list = [0, 10, 20, 30, 40, 50, 60, 100]
a_dict = {idx+1:val for idx,val in enumerate(a_list)}
print(a_dict)
output output
{1: 0, 2: 10, 3: 20, 4: 30, 5: 40, 6: 50, 7: 60, 8: 100}
I have a dictionary which has predefined keys:我有一个具有预定义键的字典:
{1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None}
and a list with numeric values:和一个带有数值的列表:
[0, 10, 20, 30, 40, 50, 60, 100]
I want to add these values from the list to the dictionary so that it will look like this:我想将列表中的这些值添加到字典中,使其看起来像这样:
{1: 0, 2: 10, 3: 20, 4: 30, 5: 40, 6: 50, 7: 60, 8: 100}
How can I add every item from the list to the next key of my dictionary?如何将列表中的每个项目添加到字典的下一个键?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.