简体   繁体   中英

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. 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. 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 :

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 :

for key, lst in zip(traffic_dict, href_lst):
    traffic_dict[key] = dict(Counter(lst))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM