How to have multiple values for a key in a python dictionary?
Solution 1
You can't have multiple items in a dictionary with the same key. What you should do is make the value a list
. Like this -
d = dict()
d["flow"] = ["flow"]
d["flow"].append("wolf")
If that is what you want to do, then you might want to use defaultdict
. Then you can do
from collections import defaultdict
d = defaultdict(list)
d["flow"].append("flow")
d["flow"].append("wolf")
Solution 2
You could use the setdefault
method to create a list as the value
for a key
even if that key
is not already in the dictionary.
So this makes the code really simple:
>>> d = {}
>>> d.setdefault(1, []).append(2)
>>> d.setdefault(1, []).append(3)
>>> d.setdefault(5, []).append(6)
>>> d
{1: [2, 3], 5: [6]}
Solution 3
You could implement a dict-like class that does exactly that.
class MultiDict:
def __init__(self):
self.dict = {}
def __setitem__(self, key, value):
try:
self.dict[key].append(value)
except KeyError:
self.dict[key] = [value]
def __getitem__(self, key):
return self.dict[key]
Here is how you can use it
d = MultiDict()
d['flow'] = 'flow'
d['flow'] = 'wolf'
d['flow'] # ['flow', 'wolf']
mourinho
Updated on June 04, 2020Comments
-
mourinho almost 4 years
I have a case where the same key could have different strings associated with it.
e.g. flow and wolf both have the same characters, if I sort them and use them as keys in a dictionary, I want to put the original strings as values.
I tried in a python dict as:
d = {} d["flow"] = flow d["flow"] = wolf
but there is only one value associated with the key.
I tried
d["flow"].append("wolf")
but that also doesn't work.How to get this scenario working with Python dicts?
-
chatton over 6 yearsYou could have the value being a List. dict["flow"] = [flow]
-
-
Olivier Melançon over 6 yearsGood job for thinking about defaultdict
-
Joe Iddon over 6 yearsOr just use
setdefault
! Much easier! But nice class anyway, +1 :) -
Olivier Melançon over 6 yearsI don't like having to rely that much on setdefault as it makes the syntax tedious, but it is a good quick fix.
-
noob_coder almost 5 yearsi was breaking my head over such a simple approach and then i found this , really helpful