【问题标题】:python identity dictionary [duplicate]python身份字典[重复]
【发布时间】:2012-01-19 16:44:33
【问题描述】:

可能重复:
How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError?

我需要defaultdict 之类的东西。但是,对于任何不在字典中的键,它应该返回键本身。

最好的方法是什么?

【问题讨论】:

  • 术语 nitpick:身份字典通常被视为使用对象身份 (id) 作为键而不是哈希的字典。
  • 啊,我没有找到其他问题。感谢您指出。有没有办法合并这两个问题?但是,对另一个问题的接受答案被证明是错误的,并且 OP 并没有费心改变他的接受。
  • @max:有一个 Stack Overflow 流程来处理重复的问题。这一切都会得到照顾=)

标签: python dictionary python-3.x


【解决方案1】:

您的意思类似于以下内容?

value = dictionary.get(key, key)

【讨论】:

  • +1 一站式解决方案,无需上课或覆盖
  • get 方法的缺点是您在整个代码中复制“找不到时返回键”规则。如果这是所有访问的规则,那么最好在容器本身中实现该功能一次(请参阅@katrielalex 的__missing__ 答案),而不是始终k 次代码。
  • 不幸的是,我忽略了它必须是一个字典(它被传递给期望调用字典方法的函数)。
【解决方案2】:

使用神奇的__missing__方法:

>>> class KeyDict(dict):
...     def __missing__(self, key):
...             return key
... 
>>> x = KeyDict()
>>> x[2]
2
>>> x[2]=0
>>> x[2]
0
>>> 

【讨论】:

    【解决方案3】:
    class Dict(dict):
        def __getitem__(self, key):
            try:
                return super(Dict, self).__getitem__(key)
            except KeyError:
                return key
    
    >>> a = Dict()
    >>> a[1]
    1
    >>> a[1] = 'foo'
    >>> a[1]
    foo
    

    如果您必须支持 Python __missing__ 方法),则此方法有效。

    【讨论】:

      猜你喜欢
      • 2020-06-14
      • 2015-08-10
      • 1970-01-01
      • 2017-03-11
      • 2018-10-16
      • 2017-09-12
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多