1

I am trying to create a dictionary from two lists, the dictionary should do a one-one mapping of each element of the listA to the corresponding element in the listB at the same index ,I have the current output and expected output below, can anyone suggest how to fix this?

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

Current output:-

{'m1': 'b3', 'm3': 'b3', 'm2': 'b3'}

Expected output:-

{'m1': 'b1', 'm2': 'b2','m3':'b3'}
user3508811
  • 847
  • 4
  • 19
  • 43

1 Answers1

6

You overwrite your dictionary values every time by doing that double iteration in your loop.

Use zip instead:

destination_milestones_gerrit_branches = dict(zip(destination_milestones, gerrit_branches))

>>> destination_milestones_gerrit_branches
{'m1': 'b1', 'm2': 'b2', 'm3': 'b3'}

If you insist on doing it through a loop, use enumerate to get the index of each 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'}
sacuL
  • 49,704
  • 8
  • 81
  • 106
  • 1
    it works but why is the order messed up meaning ,lets say for 4 elements the output is `{'m4': 'b4', 'm1': 'b1', 'm3': 'b3', 'm2': 'b2'}` instead of `{'m1': 'b1', 'm2': 'b2', 'm3': 'b3', 'm4': 'b4'}` – user3508811 Aug 06 '18 at 22:56
  • 1
    That's because dictionaries are unordered (for the most part, except in python 3.6+) – sacuL Aug 06 '18 at 22:58
  • 1
    @user3508811 [OrderedDict](https://docs.python.org/3/library/collections.html#collections.OrderedDict) provides keys order. – Lev Zakharov Aug 06 '18 at 23:04