Access dict key and return None if doesn't exist

PythonDictionary

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

You are looking for the get() method of dict.

my_var = some_var.get('some_key')

The get() method will return the value associated with 'some_key', if such a value exists. If the key is not present, then None will be returned.

Solution 3 - Python

The great thing about the .get() method is you can actually define a value to return in case the key doesn't exist.

my_dict = { 1: 'one', 2: 'two' }
print my_dict.get(3, 'Undefined key')

would print.

Undefined key

This is very helpful not only for debugging purposes, but also when parsing json (in my experience, at least), and you should prefer using get() over [] as much as possible.

Solution 4 - Python

Assuming some_var is a dictionary, you need dict.get():

my_var = some_var.get('my_key')

This result defaults to None if my_key is missing, but you can supply a different default:

my_var = some_var.get('my_key', default)

Solution 5 - Python

In python "|" is translated to "or", so:

my_var = some_var or None

Edit:

You've edited your initial post. The correct way to do what you want is:

my_var = some_var.get('my_key', None)

Solution 6 - Python

try:
    my_var = some_var
except:
    my_var = None

But honestly this probably doesn't get to the heart of what you're trying to do... We need more context to more fully answer.

Solution 7 - Python

For a new dict:

from collections import defaultdict
# None is the default, but you can change this default value
d = defaultdict(lambda: None)

For an existing dict:

from collections import defaultdict
# convert a dictionary to a defaultdict
d = defaultdict(lambda: None,d)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question9-bitsView Question on Stackoverflow
Solution 1 - PythonEndophageView Answer on Stackoverflow
Solution 2 - PythonDavid HeffernanView Answer on Stackoverflow
Solution 3 - PythonwocoburguesaView Answer on Stackoverflow
Solution 4 - PythonSven MarnachView Answer on Stackoverflow
Solution 5 - PythonS. DeveloperView Answer on Stackoverflow
Solution 6 - PythonjondavidjohnView Answer on Stackoverflow
Solution 7 - PythonshowtethView Answer on Stackoverflow