How to have multiple values for a key in a python dictionary?

*爱你&永不变心* 提交于 2020-05-09 06:04:53

问题


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?


回答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")



回答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]}



回答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']


来源:https://stackoverflow.com/questions/48845260/how-to-have-multiple-values-for-a-key-in-a-python-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!