Reputation: 33
I have 2 separate dictionaries that I want to do operations on the data with. However, I only want to operate on data which has the same key in each dictionary. For example:
Dict_McDonalds= { 'Spain' : 500 , 'UK' : 100, 'JP': 50}
Dict_BurgerKing={'Italy' : 30 , 'JP' : 50, 'Spain' : 1000}
If I want to calculate the average difference of locations both BK and McDonalds have in countries in which they both operate, how would I do that? I want to ignore countries that only one has operations in. Thanks,
Upvotes: 3
Views: 42
Reputation: 2083
You can use the fact, that keys are unique in a dict and sets have intersection methods:
d_mc= { 'Spain' : 500 , 'UK' : 100, 'JP': 50}
d_bk={'Italy' : 30 , 'JP' : 50, 'Spain' : 1000}
result = {}
for key in (set(d_mc.keys()) & set(d_bk.keys())):
result[key] = d_mc[key] - d_bk[key]
Or (thanks to the other answer by Miguel as dict comprehension:
result = {key: (d_mc[key] - d_bk[key]) for key in (set(d_mc.keys()) & set(d_bk.keys()))}
Result:
{'Spain': -500, 'JP': 0}
Upvotes: 2
Reputation: 1345
You can create a new dictionary with the distances. Iterate over the keys of one and check if it belongs to the other. Then calculate the difference.
Dict_McDonalds= { 'Spain' : 500 , 'UK' : 100, 'JP': 50}
Dict_BurgerKing={'Italy' : 30 , 'JP' : 50, 'Spain' : 1000}
diff = {}
for i in Dict_McDonalds.keys():
if i in Dict_BurgerKing.keys():
diff[i] = abs(Dict_McDonalds[i] - Dict_BurgerKing[i])
print(diff)
There is also the option of using a dictionary comprehension:
Dict_McDonalds= { 'Spain' : 500 , 'UK' : 100, 'JP': 50}
Dict_BurgerKing={'Italy' : 30 , 'JP' : 50, 'Spain' : 1000}
diff = {i:abs(Dict_McDonalds[i] - Dict_BurgerKing[i]) for i in Dict_McDonalds.keys() if i in Dict_BurgerKing.keys()}
print(diff)
output:
{'Spain': 500, 'JP': 0}
Upvotes: 3