How to set default value to all keys of a dict object in python?

后端 未结 7 794
星月不相逢
星月不相逢 2020-12-02 12:24

I know you can use setdefault(key, value) to set default value for a given key, but is there a way to set default values of all keys to some value after creating a dict ?

相关标签:
7条回答
  • 2020-12-02 12:53

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

    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)
    
    0 讨论(0)
提交回复
热议问题