In Python, a dictionary is a collection of key-value pairs. Both dictionary.get('key')
and dictionary['key']
are used to retrieve the value associated with a given key in a dictionary.
However, there is a clear difference between the two:
dictionary.get('key')
returns the value associated with the specified key if it exists in the dictionary, orNone
if the key does not exist. This means thatdictionary.get('key')
will not throw an error if the key does not exist.dictionary['key']
returns the value associated with the specified key if it exists but raises aKeyError
if the key does not exist. Thus,dictionary['key']
might crash your program when accessing nonexistent keys.
To put it short, dictionary.get('key')
is the safer way to get value from a dictionary. You shouldn’t use dictionary['key']
because it throws errors and doesn’t handle nonexistent keys.
Let’s take a closer look at how you can safely access dictionary values in Python with some code examples.
Accessing Dictionary Values in Python
There are two ways to access Python dictionary values:
dictionary['key']
dictionary.get('key')
The former approach is the simplest one but the latter one is the safest. Let’s take a look at how these approaches work and what makes the second alternative the best one.
1. dictionary[‘key’]
The most straightforward way to access a value in Python dictionary, use the square bracket accessing operator.
dict['key']
Where dict
is the name of the dictionary you’re using and ‘key
‘ is the name of the key whose value you want to read.
Here is a simple Python code example that demonstrates how to use the dict['key']
syntax to access values in a dictionary:
# Define a dictionary my_dict = { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' } # Use dict['key'] to access values in the dictionary value1 = my_dict['key1'] value2 = my_dict['key2'] value3 = my_dict['key3'] # Print the values that were retrieved print(value1) # Output: value1 print(value2) # Output: value2 print(value3) # Output: value3
In this example, we define a dictionary called my_dict
that contains three key-value pairs. Then, we use the dict['key']
syntax to retrieve the values associated with the 'key1'
, 'key2'
, and 'key3'
keys and print them.
Keep in mind that a key does not exist in my_dict
, a KeyError
is thrown. If you don’t handle this error, your program crashes. To avoid reading nonexistent values, check if a key exists before reading the value.
Here’s an example that uses the in
operator to check that the key exists:
if 'key1' in my_dict: my_value = my_dict['key1'] else: # Handle the case where the key does not exist
This code only reads the value associated with the 'key1'
key if the key exists. If the key does not exist, the else
block handles the exception in the way you want it to.
Because checking if a key exists in a dictionary is common, there’s a method, dict.get('key')
you can use to do it safely.
2. dictionary.get(‘key’)
A safe way to access a dictionary value is by using the built-in dict.get('key')
method. This method ensures the key exists before trying to access it.
Here’s what calling the method generally looks like:
dict.get('key')
Where dict
is the name of the dictionary and ‘key
‘ is the name of the key whose associated value you want to read.
If the key exists, this method returns the associated value. If the key doesn’t exist, the method returns None
by default. You will learn how to customize the default return value in just a bit.
Here is a simple Python code example that demonstrates how to use the dict.get()
method to access values in a dictionary:
# Define a dictionary my_dict = { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' } # Use dict.get() to access values in the dictionary value1 = my_dict.get('key1') value2 = my_dict.get('key2') value3 = my_dict.get('key3') # Print the values that were retrieved print(value1) # Output: value1 print(value2) # Output: value2 print(value3) # Output: value3
In this example, we define a dictionary called my_dict
that contains three key-value pairs. Then, we use the dict.get()
method to retrieve the values associated with the 'key1'
, 'key2'
, and 'key3'
and print them.
Using the dict.get()
method offers a convenient way to access dictionary values without having to check if the key exists. This allows you to write cleaner and more readable code and more importantly prevents crashes and bugs.
Default Value If Key Doesn’t Exist
To specify a custom default value for the dict.get()
method in Python, pass the default value as the second argument to dict.get()
.
For example, let’s return ‘no key
‘ instead of None
:
my_value = my_dict.get('key1', 'no key')
This tries to get the associated with the 'key1'
key from my_dict
. If 'key1'
key exists, the value is stored in my_value
. If the 'key1'
key does not exist, 'no key'
will be stored instead.
Summary
When accessing values in a dictionary in Python, it is generally recommended to use the dict.get('key')
method instead of the square brackets access operator dict['key']
. This is because dict.get('key')
is safer and more convenient to use than dict['key']
.
Thanks for reading. Happy coding!