问题
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.
回答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']
[]
回答2:
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.
回答3:
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
回答4:
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
回答5:
Both werkzeug and paste offer multidict implementations. Pick one, and use it.
回答6:
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]}
来源:https://stackoverflow.com/questions/9840783/how-do-i-turn-a-list-of-tuples-into-a-dictionary-while-keeping-redundant-values