How to combine two lists to become one. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to combine two lists to become one.

I want something like this: a = {'cats': 2, 'dogs': 4} b = {'rats': 3, 'cats': 1} to turn to this: c = {'cats': 3, 'dogs': 4, 'rats': 3}

19th Mar 2020, 7:09 PM
Tomiwa Joseph
Tomiwa Joseph - avatar
2 Answers
+ 5
You can use a dict comprehension if you like: a = {'cats': 2, 'dogs': 4} b = {'rats': 3, 'cats': 1} #c = {'cats': 3, 'dogs': 4, 'rats': 3} print({x: a.get(x, 0) + b.get(x, 0) for x in set(a) | set(b)}) # result = {'dogs': 4, 'rats': 3, 'cats': 3}
19th Mar 2020, 8:28 PM
Lothar
Lothar - avatar
0
One way of doing this is by traversing both lists. Make a new list of length = length 1+length 2, and now traverse list1 and copy it in new list after that traverse list2 and update new list accordingly.
19th Mar 2020, 7:31 PM
Vijay Meena