Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

So I've got a comprehension to the effect of:

dict((x.key, x.value) for x in y)

The problem, of course, is that if there's multiple x.keys with the same value, they get collapsed with the last x.value with that particular x.key as the only surviving member. I want to actually make the values of the resulting dict a list:

{
    'key1': ['value1'],
    'key2': ['value2', 'value3', 'value4'],
    'key3': ['value5'],
    # etc.
}

Is this logic possible with a comprehension?

like image 318
Chris Pratt Avatar asked Jul 22 '11 19:07

Chris Pratt


People also ask

Can we create dict with duplicate keys?

First, a given key can appear in a dictionary only once. Duplicate keys are not allowed. A dictionary maps each key to a corresponding value, so it doesn't make sense to map a particular key more than once.

How do you obtain a list of tuples of key value pairs in a dictionary Dict?

One of the built-in methods for dictionaries is the . items() methods, which returns a tuple of tuples of the key value pairs found inside the dictionary. We can use this method and pass it into the list() function, in order to generate a list of tuples that contain the key value pairs from our dictionary.

Can tuple have duplicate keys?

Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

Can we store duplicate keys in dictionary Python?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.


1 Answers

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.

like image 165
Eric O Lebigot Avatar answered Oct 24 '22 06:10

Eric O Lebigot