Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Dictionary return requested key if value does not exist

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.

like image 674
Nix Avatar asked May 09 '12 21:05

Nix


People also ask

What does dict return if key doesn't exist?

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.

What does Python dictionary get return if key not found?

Python dictionary method get() returns a value for the given key. If key is not available then returns default value None.

What does the get () method return when a key is not found in the dictionary none KeyError dictionary list of keys?

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.

How do you check if a key does not exist in a dictionary python?

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.


2 Answers

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'
like image 54
Mark Byers Avatar answered Nov 02 '22 20:11

Mark Byers


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'
like image 38
Moe Avatar answered Nov 02 '22 20:11

Moe