I have some dictionaries that share keys, e.g.
dict1 = {'a' : 1, 'b' : 2, 'c' : -1}
dict2 = {'a' : -1, 'b' : -3, 'c' : 3}
I would like to perform a conditional operation of both, but only change the values of the keys that meet the condition. For example I would like to add 10 to any key 'b' that has a negative value which would yield:
dict1 = {'a' : 1, 'b' : 2, 'c' : -1}
dict2 = {'a' : -1, 'b' : 7, 'c' : 3}
Is there a way to loop through 'keys' that are common to a dictionary and only operate on those? e.g.
dicts = [dict1, dict2]
for i in dicts:
if i['b'] < 0:
i['b'] = i['b'] + 10
but this yeilds the interesting result of:
print dicts[0]
print dicts[1]
{'a': 1, 'c': -1, 'b': 12}
{'a': -1, 'c': 3, 'b': -3}
Which I'm not sure I understand.
I have many (1000s) pairs of this kind of structure that are being generated in a loop so I'd like it to be fairly efficient if possible.
Thanks!
edit:
The accepted solution of
for key in set(dict1).intersection(set(dict2)):
for i in dicts:
if i[key] < 0:
i[key] = i[key] + 10
is great for 2 dicts. However if I initially had 'n' dicts that were all similar, e.g. for 4 dicts:
dict1 = {'a' : 1, 'b' : 2, 'c' : -1}
dict2 = {'a' : -1, 'b' : -3, 'c' : 3}
dict3 = {'a' : 1, 'b': -1, 'c' : -4}
dict4 = {'a' : 0, 'b': 5, 'c' : 2}
dicts = [dict1, dict2, dict3, dict4]
And the desired outcome (of only adding 10 to all negative 'b'
's) would be:
dict1 = {'a' : 1, 'b' : 2, 'c' : -1}
dict2 = {'a' : -1, 'b' : 7, 'c' : 3}
dict3 = {'a' : 1, 'b': 9, 'c' : -4}
dict4 = {'a' : 0, 'b': 5, 'c' : 2}
Would the same loop structure still apply?