I have a dictionary that looks like...
dict1 = {'England':[1,2,3,4,5,6,7],'Canada':[1,2,3,4,5,6,7]...etc}
I also have another dictionary that looks like...
dict2 = {'England':15,'Canada':10...etc}
Im trying to do a match for the key and then append the value to dict1 so I can get something like
dict3 = {'England':[1,2,3,4,5,6,7,15],'Canada':[1,2,3,4,5,6,7,10]...etc}
so far I believe I will have to use the setdefault append method. However Im not quite sure.
dict1 = {'England': range(1, 8), 'Canada': range(1, 8)}
dict2 = {'England': 15, 'Canada': 10, 'France': 5}
for k, v in dict2.items():
dict1.setdefault(k, []).append(v)
Result:
{
'Canada': [1, 2, 3, 4, 5, 6, 7, 10],
'England': [1, 2, 3, 4, 5, 6, 7, 15],
'France': [5]
}
Using dict comprehension:
dict3 = {k:v+[dict2[k]] for k,v in dict1.items() if k in dict2}
Results in:
{'England': [1, 2, 3, 4, 5, 6, 7, 15], 'Canada': [1, 2, 3, 4, 5, 6, 7, 10]}
I assume both dicts have matching keys, as you have not specified if some keys may not exist in dict2 for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With