How to change the default Python dictionary so that it always returns the default value

I use everything to print the names of the assigned IANA values ​​in a package. Thus, all dictionaries have the same default value of "RESERVED".

I do not want to use d.get(key,default), but access to dictionaries with d[key], so if the key is not in d, it returns the default value (the same for all dictionaries).

I don't have to use dictionaries, but they were an intuitive choice ... Also, a dictionary where I could do this

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

It would be a preferred solution

Tuples may be another alternative, but then I tend to bias errors by assigning values ​​... (and my code will not be a “human readable”)

Oh yes, Python 2.4

+3
3

, Mario.

, - . , "dict" , . Python, "dict" , "UserDict", Python.

:

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

+4

Python 2.5, defaultdict, . , , . , , .

+9

You can use the following class (tested in Python 2.7) Just change the zero to whatever the 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)
0
source

Source: https://habr.com/ru/post/1720755/


All Articles