2

I'm trying to add items from list to the dictionaries in another list.

info = [{'id' : 1, 'tag' : 'Football'}, {'id' : 2, 'tag' : 'MMA'}]
dates = ['May 1st', 'April 23rd']
for item in dates:
   for dic in info:
       dic['date'] = item

This is what I want to get:

[{'id': 1, 'tag': 'Football', 'date': 'May 1st'},
 {'id': 2, 'tag': 'MMA', 'date': 'April 23rd'}]

But instead of it I get this:

[{'id': 1, 'tag': 'Football', 'date': 'April 23rd'},
 {'id': 2, 'tag': 'MMA', 'date': 'April 23rd'}]

Correct me please.

lzvtmtvv
  • 129
  • 5

2 Answers2

4

If you nest the for cycles then only the last iteration of the first for matters.

The correct way to do it is cycling in parallel over the two list, using the function zip.

info = [{'id' : 1, 'tag' : 'Football'}, {'id' : 2, 'tag' : 'MMA'}]
dates = ['May 1st', 'April 23rd']
for item,dic in zip(dates,info):
    dic['date'] = item
L.A.
  • 243
  • 2
  • 12
3

You can add a new key-value pair to each dict in the list as follows:

for i in range(len(info)):
    info[i]['date'] = dates[i]
Geeky Quentin
  • 2,469
  • 2
  • 7
  • 28