如何修改Python的“默认”字典,以便它始终返回默认值 [英] How to modify the Python 'default' dictionary so that it always returns a default value

查看:351
本文介绍了如何修改Python的“默认”字典,以便它始终返回默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用它们在数据包中打印指定的IANA值的名称。所以所有的字典都有相同的默认值RESERVED。

I'm using all of them to print the names of assigned IANA values in a packet. So all of the dictionaries have the same default value "RESERVED".

我不想使用 d.get(键,默认),但访问字典 d [key] ,以便如果密钥不在d中,则返回默认值(对于所有字典都是相同的)。

I don't want to use d.get(key,default) but access dictionaries by d[key] so that if the key is not in d, it returns the default (that is same for all dictionaries).

我不一定需要使用字典,但他们是直观的选择...
另外,我可以这样做的字典

I do not necessarily need to use dictionaries, but they were the intuitive choice... Also, a dictionary where I could do this

d = {
   1..16 = "RESERVED",
   17 : "Foo",
   18 : "Bar,
   19..255: "INVALID"
  }

将是首选解决方案

元组可能是另一种选择,但是我很容易抵消错误分配值...(而且我的代码不会是可读的)

Tuples could be another alternative, but then I'm prone to offset errors assigning the values... (and my code would not be "human readable")

哦,Python 2.4

Oh yeah, Python 2.4

推荐答案

如果可以,使用 Mario的解决方案

如果你不能,你只需要子类化一个类似字典的对象。现在,你可以直接从dict继承,这样做会快速有效。对于旧的Python版本,您无法从dict继承,就有UserDict,一个纯Python字典实现。

If you can't, you just have to subclass a dictionary-like object. Now, you can do that by inheriting directly from "dict", it will be fast and efficient. For old Python versions, with which you can't inherit from "dict", there is "UserDict", a pure Python dictionary implementation.

有了它,你会做这样:

#!/usr/bin/env python
# -*- coding= UTF-8 -*-

import UserDict

class DefaultDict(UserDict.UserDict) :

    default_value = 'RESERVED'

    def __getitem__(self, key) :
        return self.data.get(key, DefaultDict.default_value)


d = DefaultDict()
d["yes"] = True;
print d["yes"]
print d["no"]

请记住,UserDict比dict慢。

Keep in mind that "UserDict" is slower than "dict".

这篇关于如何修改Python的“默认”字典,以便它始终返回默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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