我可以有一个带有同名键的字典吗? [英] Can I have a dictionary with same-name keys?

查看:67
本文介绍了我可以有一个带有同名键的字典吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有一个字典,其中的某些键可能具有相同的名称,并在这种情况下引用键时返回值列表.

I need to have a dictionary which might have same names for some keys and return a list of values when referencing the key in that case.

例如

print mydict['key']
[1,2,3,4,5,6]

推荐答案

为保持一致性,您应该将字典映射键用于值的列表(或集合),其中一些可以为空.有一个很好的成语:

For consistency, you should have the dictionary map keys to lists (or sets) of values, of which some can be empty. There is a nice idiom for this:

from collections import defaultdict
d = defaultdict(set)

d["key"].add(...)

(A defaultdict就像普通的字典,但是如果缺少键,它将在实例化它时调用您传入的参数并将结果用作默认值.因此,这将自动创建一个空的值,如果您要求一个不存在的密钥.)

(A defaultdict is like a normal dictionary, but if a key is missing it will call the argument you passed in when you instantiated it and use the result as the default value. So this will automatically create an empty set of values if you ask for a key which isn't already present.)

如果您需要该对象看起来更像是字典(即通过d["key"] = ...设置值),则可以执行以下操作. 但是,这可能不是一个好主意,因为它违背了常规的Python语法,并且很可能会在以后再次咬住您.尤其是在其他人必须维护您的代码的情况下.

If you need the object to look more like a dictionary (i.e. to set a value by d["key"] = ...) you can do the following. But this is probably a bad idea, because it goes against the normal Python syntax, and is likely to come back and bite you later. Especially if someone else has to maintain your code.

class Multidict(defaultdict):
    def __init__(self):
        super(Multidict, self).__init__(set)

    def __setitem__(self, key, value):
        if isinstance(value, (self.default_factory)): # self.default_factory is `set`
            super().__setitem__(key, value)
        else:
            self[key].append(value)

我还没有测试过.

这篇关于我可以有一个带有同名键的字典吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆