'Updating only one key value by using for loop with different different value and return the dictionary in python

Here is my current dictionary:-

my_list_of_dict = [{'A': 'a', 'B': 'b'},{'A': 'a1', B: 'b1'}]

I have values like this:-

values = ['c', 'c1']

I tried this code:-

for my_dict in my_list_of_dict:
    for value in values:
       my_dict['C'] = value

But this code returns the output as the last value:-

my_dict = {'A': 'a', 'B': 'b', 'C': 'c1'}
my_dict = {'A': 'a', 'B': 'b', 'C': 'c1'}

Expected Output is:-

my_dict = {'A': 'a', 'B': 'b', 'C': 'c'}
my_dict = {'A': 'a', 'B': 'b', 'C': 'c1'}

Where I am wrong?



Solution 1:[1]

you can use range to loop over both my_list_of_dict and values

my_list_of_dict = [{'A': 'a', 'B': 'b'},{'A': 'a1', 'B': 'b1'}]
values = ['c', 'c1']

for i in range(len(my_list_of_dict)):
    my_list_of_dict[i]['C'] = values[i]

print(my_list_of_dict)
#[{'A': 'a', 'B': 'b', 'C': 'c'}, {'A': 'a1', 'B': 'b1', 'C': 'c1'}]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1