3

I would like to create a new dictionary from dictionaries.

  • all keys in all dictionaries must be present in resulting dictionary
  • all keys must be present only once
  • value for key is highest value from all values in dictionaries

ex.

d1 = {'a':1, 'b':3}
d2 = {'a':5, 'd':5}
d3 = {'c':2, 'f':1}

d = {'a':5, 'b':3, 'c':2, 'd':5, 'f':1} 

Also, I would like keys (that are strings) to be sorted, like in my example. I try with update. However, it is overwriting existing value with the newest value, not the highest value.

4

1 回答 1

5
>>> from collections import Counter
>>> d1 = {'a':1, 'b':3}
>>> d2 = {'a':5, 'd':5}
>>> d3 = {'c':2, 'f':1}
>>> Counter(d1) | Counter(d2) | Counter(d3)
Counter({'a': 5, 'd': 5, 'b': 3, 'c': 2, 'f': 1})

This uses the union of multisets through collections.Counter

If you need the result sorted:

>>> from collections import Counter, OrderedDict
>>> OrderedDict(sorted((Counter(d1) | Counter(d2) | Counter(d3)).items()))
OrderedDict([('a', 5), ('b', 3), ('c', 2), ('d', 5), ('f', 1)])

This can be generalized for N dictionaries by using reduce

>>> from functools import reduce
>>> from operator import or_
>>> reduce(or_, map(Counter, (d1, d2, d3)))
Counter({'a': 5, 'd': 5, 'b': 3, 'c': 2, 'f': 1})
于 2013-05-26T08:29:32.417 回答