quanticle
quanticle

Reputation: 5020

How do I turn a list of tuples into a dictionary while keeping redundant values?

I'm getting a data set that's formatted as a list of key-value pairs. The key is the data source, and the value is the data element. For example:

[('a', 3), ('b', 5), ('a', 7), ('c', 15), ('d', 12)]

I want to turn this list into a dictionary. I could use Python's built-in dict(), but it throws away redundant values and keeps only the last value associated with a given key. I would like redundant values to go into a list, as follows:

{'a': [3, 7],
'b': [5],
'c': [15],
'd': [12]}

Is there a simple way to do the above? I think there has to be, but I can't seem to find the right hint via Google.

Upvotes: 2

Views: 437

Answers (6)

alan
alan

Reputation: 4842

from collections import defaultdict
l = [('a', 3), ('b', 5), ('a', 7), ('c', 15), ('d', 12)]
d = defaultdict(list)
for k, v in l:
    d[k].append(v)
print d

See the first example here: http://docs.python.org/release/2.5.2/lib/defaultdict-examples.html

Upvotes: 1

The dict subclass defaultdict in the collections module can be used to automatically initialize a new list for each key the first time you access it.

With it, you just need to loop through the input pairs and append each value to the list of the corresponding key in order to produce the lists of values you want.

import collections    

data = [('a', 3), ('b', 5), ('a', 7), ('c', 15), ('d', 12)]
result = collections.defaultdict(list)

for key, value in data:
    result[key].append(value)

print result
defaultdict(<type 'list'>, {'a': [3, 7], 'c': [15], 'b': [5], 'd': [12]})
print result['a']
[3, 7]
print result['z']
[]

Upvotes: 9

luke14free
luke14free

Reputation: 2539

like this?

 >>> d=[('a', 3), ('b', 5), ('a', 7), ('c', 15), ('d', 12)]
 >>> f={}
 >>> for k,v in d:
 ...     f[k]=f.get(k,[])+[v]
 ... 
 >>> f
 {'a': [3, 7], 'c': [15], 'b': [5], 'd': [12]}

Upvotes: 0

Marcin
Marcin

Reputation: 49816

Both werkzeug and paste offer multidict implementations. Pick one, and use it.

Upvotes: 0

Cat Plus Plus
Cat Plus Plus

Reputation: 129774

def multidict(lst):
    result = collections.defaultdict(list)
    for key, value in lst:
        result[key].append(value)
    return result # or dict(result) if you don't want to keep defaultdict

Upvotes: 3

Sven Marnach
Sven Marnach

Reputation: 601529

You can use the setdefault() method of dictionaries:

d = {}
for key, value in my_list:
    d.setdefault(key, []).append(value)

This can also be done with a defaultdict. Which of the two options is preferable depends on how d is used in the rest of the code. A defaultdict will never give you a KeyError, so it might hide errors further down in the code.

Upvotes: 14

Related Questions