note.nkmk.me

Get dictionary value from key with get() in Python

Posted: 2020-12-10 / Tags: Python, Dictionary

This article describes how to get the value from the key of a dictionary (dict type object) in Python.

  • Specify the key with [] (KeyError for non-existent keys)
  • Use dict.get() to get the default value for non-existent keys
Sponsored Link

Specify the key with [] (KeyError for non-existent keys)

In Python, you can get the dictionary value by specifying the key with dict[key].

d = {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}

print(d['key1'])
# val1
source: dict_get.py

In this case, KeyError occurs if the key does not exist.

# print(d['key4'])
# KeyError: 'key4'
source: dict_get.py

Note that it is no problem to specify a non-existent key if you want to add new element.

d['key4'] = 'val4'
print(d)
# {'key1': 'val1', 'key2': 'val2', 'key3': 'val3', 'key4': 'val4'}
source: dict_get.py

For more information about adding items to the dictionary, see the following article.

Use in to check if a key exists in the dictionary. See the following article.

Use dict.get() to get the default value for non-existent keys

You can use get() method of the dictionary object dict to get any default value without raising an error if the key does not exist.

Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.

print(d.get('key1'))
# val1

print(d.get('key5'))
# None
source: dict_get.py

You can specify the default value to be returned when the key does not exist in the second argument.

print(d.get('key5', 'NO KEY'))
# NO KEY

print(d.get('key5', 100))
# 100
source: dict_get.py

The original dictionary itself does not change.

print(d)
# {'key1': 'val1', 'key2': 'val2', 'key3': 'val3', 'key4': 'val4'}
source: dict_get.py
Sponsored Link
Share

Related Categories

Related Articles