我有以下词典列表:
d = [{'Sport': 'MLB', 'Position': 'SP', 'Age': '25'},
{'Sport': 'NBA', 'Position': 'PG', 'Age': '28'}]
Run Code Online (Sandbox Code Playgroud)
我有另一个列表,我想通过使用for循环追加到上面:
c = [{'2015 Salary' : '25'}, {'2015 Salary': '35'},
{'2016 Salary' : '30'}, {'2016 Salary' : '40'}]
Run Code Online (Sandbox Code Playgroud)
我希望最终输出
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'}}]
Run Code Online (Sandbox Code Playgroud)
这些位置总是和我使用for循环的原因相同.
您可以在更新时使用itertools.cycle重复.dc
import itertools
for existing, new_dict in zip(cycle(d), c):
existing.update(new_dict)
Run Code Online (Sandbox Code Playgroud)
cycle将列表转换为无限列表,只要它耗尽就从头开始重新启动.当压缩在一起,cycle(d)并且c配对给:
({'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'})
Run Code Online (Sandbox Code Playgroud)
然后更新d到您的预期输出.