简体   繁体   English

如何在python字典中的键具有多个值?

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

I have a case where the same key could have different strings associated with it. 我遇到的情况是,同一键可能具有与之关联的不同字符串。

eg 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. 例如flow和wolf都具有相同的字符,如果我将它们排序并将其用作字典中的键,我想将原始字符串作为值。

I tried in a python dict as: 我在python dict中尝试如下:

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. 我尝试了d["flow"].append("wolf")但这也不起作用。

How to get this scenario working with Python dicts? 如何使这种情况与Python字典一起使用?

You can't have multiple items in a dictionary with the same key. 使用相同的键,词典中不能有多个项目。 What you should do is make the value a list . 您应该做的是将值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 . 如果这是您要执行的操作,则可能要使用defaultdict Then you can do 那你可以做

from collections import defaultdict
d = defaultdict(list)
d["flow"].append("flow")
d["flow"].append("wolf")

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 . 你可以使用setdefault方法来创建一个列表作为valuekey ,即使该key不是已经在字典中

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

You could implement a dict-like class that does exactly that. 您可以实现一个类似dict的类来做到这一点。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM