Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access dict key and return None if doesn't exist

In Python what is the most efficient way to do this:

my_var = some_var['my_key'] | None 

ie. assign some_var['my_key'] to my_var if some_var contains 'my_key', otherwise make my_var be None.

like image 268
9-bits Avatar asked Feb 14 '12 22:02

9-bits


People also ask

What does dict return if key doesn't exist?

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 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 dictionary key does not exist?

How do you check if a key exists or not in a dictionary? You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key(). 2.


1 Answers

Python will throw a KeyError if the key doesn't exist in the dictionary so you can't write your code in quite the same way as your JavaScript. However, if you are operating specifically with dicts as in your example, there is a very nice function mydict.get('key', default) which attempts to get the key from the dictionary and returns the default value if the key doesn't exist.

If you just want to default to be None you don't need to explicitly pass the second argument.

Depending on what your dict contains and how often you expect to access unset keys, you may also be interested in using the defaultdict from the collections package. This takes a factory and uses it to return new values from the __missing__ magic method whenever you access a key that hasn't otherwise been explicitly set. It's particularly useful if your dict is expected to contain only one type.

from collections import defaultdict  foo = defaultdict(list) bar = foo["unset"] # bar is now a new empty list 

N.B. the docs (for 2.7.13) claim that if you don't pass an argument to defaultdict it'll return None for unset keys. When I tried it (on 2.7.10, it's just what I happened to have installed), that didn't work and I received a KeyError. YMMV. Alternatively, you can just use a lambda: defaultdict(lambda: None)

like image 131
Endophage Avatar answered Oct 08 '22 20:10

Endophage