skip to Main Content

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

2

Answers


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

    Login or Signup to reply.
  2. 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))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search