-3

I have the following list of dictionaries:

d = [{'Sport': 'MLB', 'Position': 'SP', 'Age': '25'},
     {'Sport': 'NBA', 'Position': 'PG', 'Age': '28'}]

I have another list that i would like to append to the above by using a for loop:

c = [{'2015 Salary' : '25'}, {'2015 Salary': '35'},
    {'2016 Salary' : '30'}, {'2016 Salary' : '40'}]

I would like the final output to be

e = [{'Sport': 'MLB', 'Position': 'SP', 'Age': '25', '2015 Salary': '25',  
     '2016 Salary': '30'},
     {'Sport': 'NBA', 'Position': 'PG', 'Age': '28', '2015 Salary': '35',  
     '2016 Salary': '40'}}]

The positions would always be the same thats why i was going to use a for loop.

MoxieBall
  • 1,907
  • 7
  • 23
skimchi1993
  • 189
  • 2
  • 9

4 Answers4

7

You could use itertools.cycle to repeat over d while updating from c.

import itertools

for existing, new_dict in zip(cycle(d), c):
    existing.update(new_dict)

cycle turns a list into an infinite list by restarting from the beginning whenever it is exhausted. When you zip them together, cycle(d) and c pair up to give:

({'Sport': 'MLB', 'Position': 'SP', 'Age': '25'}, {' 2015 Salary' : '25'})
({'Sport': 'NBA', 'Position': 'PG', 'Age': '28'}, {'2015 Salary': '35'})
({'Sport': 'MLB', 'Position': 'SP', 'Age': '25'}, {'2016 Salary ': '30'})
({'Sport': 'NBA', 'Position': 'PG', 'Age': '28'}, {'2016 Salary' : '40'})

Which then update d to your expected output.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
1

You can achieve it by:

for i, current_d in enumerate(d):
    current_l = c[i::2]
    for e in current_l:
        current_d.update(e)

d will contain the information that you want.

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
1

Hope this may help

for i in range(len(d)):
     for j in range(i,len(c),i+2):
             d[i].update(c[j])
Ravinder Baid
  • 395
  • 1
  • 15
1

Here is my one-line style solution using comprehensions, without any needed import, and which works also whatever the length of d input:

d = [{'Sport': 'MLB', 'Position': 'SP', 'Age': '25'},
     {'Sport': 'NBA', 'Position': 'PG', 'Age': '28'}]

c = [{'2015 Salary': '25'}, {'2015 Salary': '35'},
     {'2016 Salary': '30'}, {'2016 Salary': '40'}]

result = [{k:v for i in ([d[j]] + c[j::len(d)]) for k,v in i.items()} for j in range(len(d))]

print(result)
# [{'Sport': 'MLB', 'Position': 'SP', 'Age': '25', '2015 Salary': '25', '2016 Salary': '30'},
#  {'Sport': 'NBA', 'Position': 'PG', 'Age': '28', '2015 Salary': '35', '2016 Salary': '40'}]
Laurent H.
  • 6,316
  • 1
  • 18
  • 40