pythonfor-looppass-by-referencepass-by-value

Combining two lists into a list of dictionaries and all the values are the same


I have two lists I want to combine :

old = ['aaa', 'bbb', 'ccc']
new = ['AAA', 'BBB', 'CCC']

and I want to make a list of dict as shown below :

myList = [{'lama': 'aaa', 'baru': 'AAA'}, {'lama': 'bbb', 'baru': 'BBB'}, {'lama': 'ccc', 'baru': 'CCC'}]

what I tried was :

myList = []
myDict = {}

old = ['aaa', 'bbb', 'ccc']
new = ['AAA', 'BBB', 'CCC']


for idx, value in enumerate(old):
    myDict['lama'] = old[idx]
    myDict['baru'] = new[idx]

    myList.append(myDict)
    
print(myList)

and the result is :

[{'lama': 'ccc', 'baru': 'CCC'}, {'lama': 'ccc', 'baru': 'CCC'}, {'lama': 'ccc', 'baru': 'CCC'}]

what should I do to get the result I want? Thanks


Solution

  • Try

    myList = [{'lama': i, 'baru': j} for i, j in zip(old, new)]