I am looking for an easy way to be able to get a value from a dictionary, and if its not there, return the key that the user passed in.
E.g.:
>>> 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'
These will always be strings, but basically I am creating a language map and need an easy way to get a value, if it exists return it else return the key.
Is there any easy way to do this? Or should I just extend dict and do it manually.
The get() method is a dictionary method that returns the value of the associated key. If the key is not present it returns either a default value (if passed) or it returns None. Using this method we can pass a key and check if a key exists in the python dictionary.
Python dictionary method get() returns a value for the given key. If key is not available then returns default value None.
get() method returns a default value if the key is missing. However, if the key is not found when you use dict[key] , KeyError exception is raised.
Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.
I don't think defaultdict
will help you here because the function that generates the default value does not have access to which key was requested.
However you use an ordinary dictionary and use get
with a default value:
>>> lookup = {}
>>> key = 'DNE'
>>> lookup.get(key, key)
'DNE'
Should be possible with a lambda function
from collections import defaultdict
a = defaultdict((lambda : 'DNE'))
Edit: Sorry I misread the question. As the comment above already said. The way to go is extending the dict class.
>>> class mydict(dict):
... def __missing__(self,key):
... return key
...
>>> a = mydict()
>>> a['asd']
'asd'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With