Search code examples
python-3.xlistdictionaryreferencevariable-assignment

Assign values from list to specific values in a list of dictionaries


I have list of values:

list = [value1, value2, value3]

And a list of dictionaries where on specific keys I must set the corresponding values:

dictionaries = [{"key1":{"key2":{"key3":position_value1}}},{"key1":{"key2":{"key3":position_value2}}}]

I'm trying to assign the values avoiding solutions that requires do explicit iteration over the numerical indexes of list and dictionaries.

I find the next pseudo-solution iterating over two iterables at the same time using for-each loops

for (dict, value) in zip(dictionaries, list):
    dict['key1']['key2']['key3'] = value
print(dictionaries)

But doesn't work due to, all dictionaries take only the last value of the list of values, obtaining the next result:

[{"key1":{"key2":{"key3":position_value3}}},{"key1":{"key2":{"key3":position_value3}}}]

It's important to note that when creating the list of dictionaries the dict.copy() method was used, but maybe this doesn't take affect in the reference allocated in nested dictionaries.

Dictionary list creation

base_dict = {"key1": {"key2":{"key3": None}}}
dictionaries = [base_dict.copy() for n in range(3)]

I appreciate any compact solution, even solutions based on unpacking.


Solution

  • base_dict = {"key1": {"key2":{"key3": None}}}
    dictionaries = [base_dict.copy() for n in range(3)]
    

    Will create shallow copies of base_dict. That means that while these are indepenedent at the top level, their values are copied by reference; hence, the inner dictionaries {"key2":{"key3": None}} are still all the same object. When rebinding key3, all references will be affected.

    You can avoid that by making a deepcopy:

    from copy import deepcopy
    
    dictionaries = [deepcopy(base_dict) for _ in range(3)]