Store Multiple Values For One Key In Dictionary
I have a list of data, which has 2 values: a 12 a 11 a 5 a 12 a 11 I would like to use a dictionary, so I can end up with a list of values for each of the key. Colu
Solution 1:
Python dicts can have only one value for a key, so you cannot assign multiple values in the fashion you are trying to.
Instead, store the mutiple values in a list corresponding to the key so that the list becomes the one value corresponding to the key:
d = {}
d["a"] = []
d["a"].append(1)
d["a"].append(2)
>>> print d
{'a': [1, 2]}
You can use a defaultdict
to simplify this, which will initialise the key if it doesn't exist with an empty list as below:
from collections import defaultdict
d = defaultdict(list)
d["a"].append(1)
d["a"].append(2)
>>> print d
defaultdict(<type'list'>, {'a': [1, 2]})
If you don't want repeat values for a key, you can use a set instead of list. But do note that a set
is unordered.
from collections import defaultdict
d = defaultdict(set)
d["a"].add(1)
d["a"].add(2)
d["a"].add(1)
>>> print d
defaultdict(<type'set'>, {'a': set([1, 2])})
If you need to maintain order, either use sorted at runtime, or use a list with an if clause to check for values
from collections import defaultdict
d = defaultdict(list)
for item in (1, 2, 1, 2, 3, 4, 1, 2):
if item notin d["a"]:
d["a"].append(item)
>>> print d
defaultdict(<type'list'>, {'a': [1, 2, 3, 4]})
Post a Comment for "Store Multiple Values For One Key In Dictionary"