Reputation: 21
I am beginner with python. I have a list. I want to loop over values of list and add each to my dictionary values respectively. It looked simple but I tried to write few loops but none was working for me. For example
Note : Total number of element in My_list and total number of key:value pairs in My_Dict are same.
My_list= [ [A,B,C], [D,E,F], [I,J,K] ]
My_dict= { 'Apple'= {'Color'=[data1,data2]} , 'Orange'= {'Color'=[data3,data4]}, 'Peach'={ 'color'=[data5,data6]} }
I was trying to get following format by adding each element of My_list to respective value of dictionary.
New_Dict= { 'Apple'= { 'Name'=[A,B,C], 'Color'=[data1,data2]} , 'Orange'= { 'Name'=[D,E,F] ,'Color'=[data3,data4]}, 'Peach'={ 'Name'=[I,J,K], 'color'=[data5,data6]} }
Upvotes: 0
Views: 80
Reputation: 94941
As suggested in the comments, you need to use a collections.OrderedDict
instead of regular dict
in order to preserve the ordering of my_dict
. From there, you can use zip
to iterate over the keys in my_dict
and the elements of my_list
in lockstep, and insert each item in my_list
to the appropriate place in the OrderedDict
:
from collections import OrderedDict
my_list = [['A', 'B', 'C'], ['D', 'E', 'F'], ['I', 'J', 'K']]
my_dict = OrderedDict([
('Apple', {'Color' : ['data1','data2']}),
('Orange', {'Color' : ['data3','data4']}),
('Peach', { 'color' : ['data5','data6']}),
])
for key, name in zip(my_dict, my_list):
my_dict[key]['Name'] = name
print(my_dict)
Output:
OrderedDict([('Apple', {'Color': ['data1', 'data2'], 'Name': ['A', 'B', 'C']}), ('Orange', {'Color': ['data3', 'data4'], 'Name': ['D', 'E', 'F']}), ('Peach', {'color': ['data5', 'data6'], 'Name': ['I', 'J', 'K']})])
Upvotes: 1