How to modify the Python 'default' dictionary so that it always returns a default value

不打扰是莪最后的温柔 提交于 2019-12-04 14:48:29
e-satis

If you can, use Mario's solution.

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.

With it, you would do it this way :

#!/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"]

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

If you can migrate to Python 2.5, there is the defaultdict class, as shown here. You can pass it an initializer that returns what you want. Otherwise, you'll have to roll your own implementation of it, I fear.

You can use the following class (tested in Python 2.7) Just change zero to any default value you like.

class cDefaultDict(dict):
    # dictionary that returns zero for missing keys
    # keys with zero values are not stored

    def __missing__(self,key):
        return 0

    def __setitem__(self, key, value):
        if value==0:
            if key in self:  # returns zero anyway, so no need to store it
                del self[key]
        else:
            dict.__setitem__(self, key, value)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!