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.
The
dictsubclassdefaultdictin thecollectionsmodule can be used to automatically initialize a newlistfor 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
listof the corresponding key in order to produce the lists of values you want.