我正在尝试从两个列表创建一个字典,该字典应该将listA的每个元素与listB中具有相同索引的对应元素进行一对一映射,我在下面有当前输出和预期输出,有人可以建议如何解决此问题吗?
destination_milestones_gerrit_branches ={}
destination_milestones =['m1','m2','m3']
gerrit_branches = ['b1','b2','b3']
for milestone in destination_milestones:
print milestone
for branch in gerrit_branches:
print branch
destination_milestones_gerrit_branches[milestone]= branch
print destination_milestones_gerrit_branches
当前输出:-
{'m1': 'b3', 'm3': 'b3', 'm2': 'b3'}
预期输出:-
{'m1': 'b1', 'm2': 'b2','m3':'b3'}
答案 0 :(得分:5)
您每次通过在循环中执行两次迭代来覆盖字典值。
改为使用zip
:
destination_milestones_gerrit_branches = dict(zip(destination_milestones, gerrit_branches))
>>> destination_milestones_gerrit_branches
{'m1': 'b1', 'm2': 'b2', 'm3': 'b3'}
如果您坚持要通过循环执行此操作,请使用enumerate
获取每个destination_milestones
的索引:
destination_milestones_gerrit_branches ={}
for i, milestone in enumerate(destination_milestones):
destination_milestones_gerrit_branches[milestone]= gerrit_branches[i]
>>> destination_milestones_gerrit_branches
{'m1': 'b1', 'm2': 'b2', 'm3': 'b3'}