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?
解决方案
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")