Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching Python Dict

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.

like image 633
Ravash Jalil Avatar asked Jun 18 '26 14:06

Ravash Jalil


2 Answers

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]
}
like image 130
JuniorCompressor Avatar answered Jun 20 '26 03:06

JuniorCompressor


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.

like image 33
Marcin Avatar answered Jun 20 '26 04:06

Marcin