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!
Aucun commentaire:
Enregistrer un commentaire