Refael
Refael

Reputation: 19

Python - merge two lists of tuples into one list of tuples

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)]

Upvotes: 0

Views: 414

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121744

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.

Upvotes: 3

Related Questions