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

67 views Asked by At

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

2

There are 2 answers

2
Beitian Ma On BEST ANSWER

Try

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

Your code has just one tiny problem where you initialize your dictionary. The repeated updates change the original dictionary in place so if you initialize it in the loop, it should work.

myList = []

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


for idx, value in enumerate(old):
    myDict = {}
    myDict['lama'] = old[idx]
    myDict['baru'] = new[idx]
    print(myDict)
    myList.append(myDict)
    
print(myList)

You can also use zip to traverse lists with the same length simultaneously.

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

myList = []

for x,y in zip(old, new):
  myList.append({"lama": x, "baru":y})

Here's the output:

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