0

What's the pythonic way of achieving the following?

from:

a = [('apple', 10), ('of', 10)]
b = [('orange', 10), ('of', 7)]

to get

c = [('orange', 10), ('of', 17), ('apple', 10)]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Refael
  • 19
  • 2

1 Answers1

3

You essentially have word-counter pairs. Using collections.Counter() lets you handle those in a natural, Pythonic way:

from collections import Counter

c = (Counter(dict(a)) + Counter(dict(b))).items()

Also see Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

Demo:

>>> from collections import Counter
>>> a = [('apple', 10), ('of', 10)]
>>> b = [('orange', 10), ('of', 7)]
>>> Counter(dict(a)) + Counter(dict(b))
Counter({'of': 17, 'orange': 10, 'apple': 10})
>>> (Counter(dict(a)) + Counter(dict(b))).items()
[('orange', 10), ('of', 17), ('apple', 10)]

You could just drop the .items() call and keep using a Counter() here.

You may want to avoid building (word, count) tuples to begin with and work with Counter() objects from the start.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Any nice way to avoid the intermediate dictionaries? I couldn't think of one, too ... – dhke Dec 10 '15 at 16:42
  • 2
    @dhke: no 'nice' way, it is the most concise way to convert the list of (word, count) tuples to a `Counter`. – Martijn Pieters Dec 10 '15 at 16:42
  • @MartijnPieters I was thinking of `Counter.update()` but that actually behaves differently than `dict.update()` when passed a tuple sequence. – dhke Dec 10 '15 at 16:45