Creating a dict from list of key, value tuples while maintaining duplicate keys

You can add the elements one by one to a dictionary that contains empty lists by default:

import collections

result_dict = collections.defaultdict(list)
for x in y:
    result_dict[x.key].append(x.value)

You can also do something very similar without having to use the collections module:

result_dict = {}
for x in y:
    result_dict.setdefault(x.key, []).append(x.value)

but this is arguably slightly less legible.

An equivalent, more legible (no need to “parse” the less common setdefault) but more pedestrian, base Python approach is:

result_dict = {}
for x in y:
    if x.key not in result_dict:
        result_dict[x.key] = []
    result_dict[x.key].append(x.value)

The first solution is clearly the preferred one, as it is at the same time concise, legible, and fast.

Leave a Comment