+ 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}
3 Respuestas
+ 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}
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.