I have two dictionary that look like:
{'r': 2, 'e': 4, 'h': 2, 'k': 4}
and
{'r': 2, 'e': 5, 'y': 2, 'h': 2}
how do I get a dictionary that has all the keys but incase there are keys in both initial dictionaries it keeps the higher value for that key? I want a dictionary that looks like this:
{'e': 5, 'k': 4, 'y': 2, 'h': 2, 'r': 2}
None of the previous answers helped me.
You can use
itertools.chainto combine all values thenitertools.groupbyto get all the values for each individual key and just take the max of those values. You will need to sort the merged data before using groupby for it to work correctly though. Also I'm usingoperator.itemgetterto get the keys and values instead of lambdas so you could just replace them with lambdas if you don't want to import another library although I wouldn't advise it as it is slower and no real need to use them really.Another alternative here is
collections.defaultdictand to ensure you always get the correct output to include if there are negative values usefloat('-inf')as the default value:Or without any imports
dict.setdefaultcan basically take the place ofdefaultdict:Lastly, using
pandas