Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return None if Dictionary key is not available

I need a way to get a dictionary value if its key exists, or simply return None, if it does not.

However, Python raises a KeyError exception if you search for a key that does not exist. I know that I can check for the key, but I am looking for something more explicit. Is there a way to just return None if the key does not exist?

like image 300
Spyros Avatar asked May 25 '11 20:05

Spyros


People also ask

What will a dictionary return if key not found?

If given key does not exists in dictionary, then it returns the passed default value argument. If given key does not exists in dictionary and Default value is also not provided, then it returns None.

What does Python dictionary get return if key not found?

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

How do you check if dictionary key does not exist?

You can check if a key exists in a dictionary using the keys() method and IN operator. The keys() method will return a list of keys available in the dictionary and IF , IN statement will check if the passed key is available in the list. If the key exists, it returns True else, it returns False .

Which dictionary method returns a default value if a key doesn't exist?

Use the dict. get() method to return a default value if a key is not in the dictionary, e.g. my_dict. get('key_name', 'default') . The dict.


2 Answers

You can use dict.get()

value = d.get(key) 

which will return None if key is not in d. You can also provide a different default value that will be returned instead of None:

value = d.get(key, "empty") 
like image 127
Tim Pietzcker Avatar answered Oct 14 '22 01:10

Tim Pietzcker


Wonder no more. It's built into the language.

     >>> help(dict)      Help on class dict in module builtins:      class dict(object)      |  dict() -> new empty dictionary      |  dict(mapping) -> new dictionary initialized from a mapping object's      |      (key, value) pairs     ...      |        |  get(...)      |      D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.      |       ... 
like image 25
John La Rooy Avatar answered Oct 14 '22 00:10

John La Rooy