Reputation: 1739
I'm merging a set of dictionaries, and two of them may contain the same key but different values. Currently, my simple code looks something like:
dictOne = {'income': 10000, 'name': 'John'}
dictTwo = {'income': 6000, 'job': 'plumber'}
resultsDict = {}
myList = [dictOne, dictTwo]
for i in myList:
resultsDict.update(i)
The value of the income key in resultsDict
will always be whatever the value was in the most recently added dictionary where the same key is present (in this case it would be 6000).
What is the easiest/most elegant way to control the update of a given duplicate key? For example, don't add the new key/value if the key is already present, or don't update the key's value if the value to be updated is larger than the one already in the dict I'm updating?
Upvotes: 0
Views: 788
Reputation: 2017
You could just add both keys and values into one dictionary. dictTwo = {'incomeOne': 10000, 'incomeTwo': 6000, etc...} then pull them out accordingly.
Upvotes: 0
Reputation: 11691
I believe you have to actually loop over all the dictionaries individually, check if the key is there, when it's not there or when it is but lower than the new value, update appropriately
for currDict in myList:
for key, val in currDict.items():
try:
val = float(val)
except ValueError:
continue
try:
if resultsDict[key] < val:
resultsDict[key] = val
except KeyError:
resultsDict[key] = val
NOTE: I change the nomenclature of i
for readability
UPDATE: This code does NOT cover the case of when val
does not contain numbers (or anything that can be float
-ed). You did not specify how you wanted that case to behave so this simply ignores that
Upvotes: 1