[英]change dictionary values to dictionaries from list of dictionaries in python
I have a list with 12 dictionaries, and the main dictionary with 12 keys.我有一个包含 12 个字典的列表,以及包含 12 个键的主字典。 For every key in the main dictionary, I want to change the value to dictionary from the list of the dictionaries that I have.
对于主字典中的每个键,我想从我拥有的字典列表中将值更改为字典。 I have tried this but it doesn't work:
我已经尝试过了,但它不起作用:
values = []
for lst in href_lst:
val = dict(Counter(lst))
values.append(val)
for key in traffic_dict:
for dict in values:
traffic_dict[key] = dict
The output is that every key in the main dictionary has the same value. output 是主字典中的每个键都有相同的值。 I need for every key a different value (different dictionary from the list).
我需要为每个键提供不同的值(列表中的不同字典)。
This is because your second loop here这是因为你的第二个循环在这里
for key in traffic_dict:
for dict in values:
traffic_dict[key] = dict
is running even after assigning the value.即使在分配值之后也正在运行。 This will assign the last value in the list "values" to every "key".
这会将列表“值”中的最后一个值分配给每个“键”。
Corrected code sample,更正的代码示例,
i = 0
for key in traffic_dict:
traffic_dict[key] = values[i]
i += 1
There can be multiple ways to do this.可以有多种方法来做到这一点。 The above code is one of the ways.
上面的代码就是其中一种方式。
You could use a list comprehension and zip
:您可以使用列表理解和
zip
:
values = [dict(Counter(lst)) for lst in href_lst]
for key, value in zip(traffic_dict, values):
traffic_dict[key] = value
Or, if you don't need values
later, just zip
:或者,如果您以后不需要
values
,只需zip
:
for key, lst in zip(traffic_dict, href_lst):
traffic_dict[key] = dict(Counter(lst))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.