Python Dictionary returns the requested key if the value does not exist

I am looking for an easy way to get the value from the dictionary, and if it is not there, return the key that the user passed.

eg:.

>>> lookup = defaultdict(magic)
>>> print lookup['DNE']
'DNE'
>>> print lookup.get('DNE')
'DNE'
>>> print lookup['exists']
'some other value'
>>> print lookup.get('exists')
'some other value'

They will always be strings, but basically I create a language map and need an easy way to get the value, if it exists, return it, otherwise return the key.

Is there an easy way to do this? Or I just need to expand the dict and do it manually.

+5
source share
3 answers

Perhaps using the lambda function

from collections import defaultdict
a = defaultdict((lambda : 'DNE'))

Edit: Sorry, I misunderstood the question. As mentioned above. The way to this is to extend the dict class.

>>> class mydict(dict):
...     def __missing__(self,key):
...         return key
... 
>>> a = mydict()
>>> a['asd']
'asd'
+2
source

, defaultdict , , , , .

get :

>>> lookup = {}
>>> key = 'DNE'
>>> lookup.get(key, key)
'DNE'
+14

This works under Python 2.7 at least:

from collections import defaultdict

class KeyAwareDefaultDict(defaultdict):
    def __missing__(self, key):
        if self.default_factory is None:
            raise KeyError(key)
        self[key] = value = self.default_factory(key)
        return value

lookup = KeyAwareDefaultDict((lambda key: key))

Unlike the standard dict, defaultdict.get () also seems to call __missing__, so it makes a better basis for the extension.

+2
source

All Articles