How To Check if a Given Key Already Exists in a Dictionary

How To Check if a Given Key Already Exists in a Dictionary

Two different ways to check

Image for postPhoto by Pisit Heng on Unsplash

A dictionary is a mutable ? it has an unordered set of keys and values. Knowing how to check if a key exists is critical, both prior to assigning values, to avoid overwriting existing data, and when accessing values, to ensure the key exists.

Use the in keyword or the .get() method to inspect a dictionary for a given key.

The ?in? Keyword

In Python, the in keyword queries an iterable for a specified value. In the event the iterable is a list, the values will be queried. For example:

person = { “first_name”: “Sarah”, “last_name”: “Kerrigan”, “nickname”: “Queen of Blades”}print(“nickname” in person.keys()) # Trueprint(“age” in person.keys()) # False

Notice that the .keys() method is used to return the keys from our dictionary as a list of strings. We can speed this technique up because in may also be used directly with dictionaries. When querying a dictionary, the keys, and not the values, are searched.

person = { “first_name”: “Sarah”, “last_name”: “Kerrigan”, “nickname”: “Queen of Blades”}print(“nickname” in person) # Trueprint(“age” in person) # False

The .get() Method

Referencing a key that does not exist in a dictionary will cause a KeyError exception, potentially breaking your code.

person = { “first_name”: “Sarah”, “last_name”: “Kerrigan”, “nickname”: “Queen of Blades”}print(person[‘age’])”””Traceback (most recent call last): File “medium.py”, line 7, in <module> print(person[‘age’])KeyError: ‘age'”””

To avoid this scenario, you could use the above method to check for a key first. However, this can become very repetitive.

person = { “first_name”: “Sarah”, “last_name”: “Kerrigan”, “nickname”: “Queen of Blades”}if “age” in person: print(person[‘age’])if “first_name” and “last_name” in person: print(first_name + ” ” + last_name)

Alternatively, use .get() which will not cause an exception if the key does not exist. The method requires a single string (the key that will be retrieved) and accepts an optional second argument, which will be used as the default value when the key is not found. When a default value is not specified, None will be returned by .get() when the key is not found.

person = { “first_name”: “Sarah”, “last_name”: “Kerrigan”, “nickname”: “Queen of Blades”}middle_name = person.get(“middle_name”,””) # empty stringprint(person.get(“age”)) # None

11

No Responses

Write a response