Python checking if key exists in dict

Python: Check if Key Exists in Dictionary

Dictionary (also known as “map”, “hash” or “associative array”) is a built-in Python container that stores elements as a key-value pair.

Just like other containers have numeric indexing, here we use keys as indexes. Keys can be numeric or string values. However, no mutable sequence or object can be used as a key, like a list.

In this article, we’ll take a look at how to check if a key exists in a dictionary in Python.

In the examples, we’ll be using this fruits_dict dictionary:

fruits_dict = dict(apple= 1, mango= 3, banana= 4) 

Check if Key Exists using in Operator

The simplest way to check if a key exists in a dictionary is to use the in operator. It’s a special operator used to evaluate the membership of a value.

Here it will either evaluate to True if the key exists or to False if it doesn’t:

key = 'orange' if key in fruits_dict: print('Key Found') else: print('Key not found') 

Now, since we don’t have an orange in our dictionary, this is the result:

This is the intended and preferred approach by most developers. Under the hood, it uses the __contains__() function to check if a given key is in a dictionary or not.

Читайте также:  Shell script and python

Check if Key Exists using get()

The get() function accepts a key , and an optional value to be returned if the key isn’t found. By default, this optional value is None . We can try getting a key, and if the returned value is None , that means it’s not present in the dictionary:

key = 'orange' if fruits_dict.get(key) == None: print('Key not found') else: print('Key found') 

Check if Key Exists using keys()

The keys() function returns the keys from our dictionary as a sequence:

dict_keys(['apple', 'mango', 'banana']) 

Using this sequence, we can check if the key is present. You can do this through a loop, or better yet, use the in operator:

key = 'orange' if key in fruits_dict.keys(): print('Key found') else: print('Key not found') 

Check if Key Exists using has_key()

Instead of manually getting the keys and running a check if the value we’re searching for is present, we can use the short-hand has_key() function:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

key = 'orange' if fruits_dict.has_key(key): print('Key found') else: print('Key not found') 

It returns True or False , based on the presence of the key. This code outputs:

Handling ‘KeyError’ Exception

An interesting way to avoid problems with a non-existing key or in other words to check if a key exists in our dictionary or not is to use the try and except clause to handle the KeyError exception.

The following exception is raised whenever our program fails to locate the respective key in the dictionary.

It is a simple, elegant, and fast way to handle key searching:

try: fruits_dictPython checking if key exists in dict except KeyError as err: print('Key not found') 

This approach, although it may sound unintuitive, is actually significantly faster than some other approaches we’ve covered so far.

Note: Please note, exceptions shouldn’t be used to alter code flow or to implement logic. They fire really fast, but recovering from them is really slow. This approach shouldn’t be favored over other approaches, when possible.

Let’s compare the performance of them to get a better idea of how fast they can execute.

Performance Comparison

import timeit code_setup = """ key = 'orange' fruits_dict = dict(apple= 1, mango= 3, banana= 4) """ code_1 = """ if key in fruits_dict: # print('Key Found') pass else: # print('Key not found') pass """ code_2 = """ if fruits_dict.get(key): # print('Key found') pass else: # print('Key not found') pass """ code_3 = """ if fruits_dict.__contains__(key): # print('Key found') pass else: # print('Key not found') pass """ code_4 = """ try: # fruits_dictPython checking if key exists in dict pass except KeyError as err: # print('Key not found') pass """ code_5 = """ if key in fruits_dict.keys(): # print('Key found') pass else: # print('Key not found') pass """ print('Time of code_1: ', timeit.timeit(setup = code_setup , stmt= code_1, number= 10000000)) print('Time of code_2: ', timeit.timeit(setup = code_setup , stmt= code_2, number= 10000000)) print('Time of code_3: ', timeit.timeit(setup = code_setup , stmt= code_3, number= 10000000)) print('Time of code_4: ', timeit.timeit(setup = code_setup , stmt= code_4, number= 10000000)) print('Time of code_5: ', timeit.timeit(setup = code_setup , stmt= code_5, number= 10000000)) 
Time of code_1: 0.2753713619995324 Time of code_2: 0.8163219139996727 Time of code_3: 0.5563563220002834 Time of code_4: 0.1561058730003424 Time of code_5: 0.7869278369998938 

The most popular choice and approach, of using the in operator is fairly fast, and it’s also the intended approach for solving this problem.

Conclusion

In this article, we discussed multiple ways to check if a key exists in our dictionary or not. Then we made a performance comparison.

Источник

How to Check if a Key Exists in a Dictionary in Python – Python Dict Has Key

Hillary Nyakundi

Hillary Nyakundi

How to Check if a Key Exists in a Dictionary in Python – Python Dict Has Key

Python is one of the most popular programming languages today. Its usage cuts across multiple fields, but the most common ones are data science, machine learning, and web development.

When you’re coding in Python, you’ll use different data structures. In Python, among the most used is the dictionary.

A dictionary is a collection of key-value pairs that allows you to store and retrieve data.

When working with dictionaries, it’s a common practice to check if a key exists or not. This can be most helpful when you are working with a large dataset and need to access values based on their keys.

In this article, we are going to explore different ways that we can use to check if a key exists in a dictionary in Python. Let’s get started.

Method 1: Using the in Operator

You can use the in operator to check if a key exists in a dictionary. It’s one of the most straightforward ways of accomplishing the task. When used, it returns either a True if present and a False if otherwise.

You can see an example of how to use it below:

my_dict = if 'key1' in my_dict: print("Key exists in the dictionary.") else: print("Key does not exist in the dictionary.") 

From the code sample above, we check if key1 exists in my_dict . If it does, then the confirmation message will be displayed. If not, the message indicating the key does not exist gets printed.

Method 2: Using the dict.get() Method

The dict.get() method will return the value associated with a given key if it exists and None if the requested key is not found.

my_dict = if my_dict.get('key1') is not None: print("Key exists in the dictionary.") else: print("Key does not exist in the dictionary.") 

From the code sample above, we used the dict.get() method to get the values associated with key1 . If the requested key is present, the my_dict.get(‘key1’) is not None evaluates to True, meaning the requested key is present.

Method 3: Using Exception Handling

Exception handling allows you to first try and access the value of the key and handle the KeyError exception if it occurs.

my_dict = try: value = my_dict['key1'] print("Key exists in the dictionary.") except KeyError: print("Key does not exist in the dictionary.") 

The code sample above allows us to access the value associated with key1 . If it exists, the code inside try executes and the message gets printed. But if the KeyError exception occurs, then it means the key does not exist and the code inside the except block will be executed.

Additional Points

  • Key exists versus value exists
    The methods we have discussed above only check if a key exists. If we were to check if a value is present, we will need to iterate through the values using methods like dictname.values() .
  • Performance considerations
    Different methods may have different performance implications depending on the size of your dictionary. Generally the in operator is best for small to medium-sized dictionaries while dict.get() and exemption handling are a good fit for large dictionaries.
  • Combining methods
    A good thing about working with Python dictionary methods is that you can combine them. For example, you can use the in operator to check if a key exists and the dict.get() to retrieve its value if it exists.
  • Using dict.setdefault()
    It allows you to check if a key exists and returns the value if present. In case the key is missing, then you can set a default value while adding it to the dictionary at the same time.

With an understanding of the above points and good practice using these methods, you should be comfortable working with dictionaries in Python.

Hillary Nyakundi

Hillary Nyakundi

Technical Writer ✍️ & Open-Source Enthusiast ❤ || Empowering Developers to Learn & Grow || Committed to Making a Meaningful Contribution to the Tech Community and Beyond.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

Оцените статью