Python 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:

Читайте также:  Python add array element by element

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.

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 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 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.

Источник

Проверить, существует ли данный ключ в словаре Python

В этом посте будет обсуждаться, как проверить, существует ли данный ключ в словаре Python.

1. Использование в операторе

Предпочтительный и самый быстрый способ проверить наличие ключа в словаре — использовать in оператор. Он возвращается True если ключ есть в словаре, False в противном случае.

The in оператор реализует встроенную функцию __contains__ . Однако вызывать __contains__ напрямую. in оператор — это Pythonic способ вызвать __contains__ функция.

2. Использование dict.get() функция

Другим распространенным подходом к поиску ключа в словаре является использование get() функция. Это возвращает значение ключа, если оно найдено; в противном случае указанное значение или значение по умолчанию None возвращается.

3. Использование блока try/except

Вы также можете использовать dPython dict проверка существования ключа синтаксис для проверки ключа в словаре. Это вызывает KeyError когда указанный ключ не существует в словаре. Чтобы справиться с этим, используйте блок try/except, как показано ниже:

4. Использование setdefault() функция

Наконец, вы можете использовать встроенную функцию setdefault() , который вставляет ключ, только если он не найден в словаре. Это особенно полезно, когда вам нужно вставить ключ, только если он еще не существует в словаре.

Это все, что касается определения того, существует ли данный ключ в словаре Python.

Средний рейтинг 5 /5. Подсчет голосов: 24

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

Источник

How to Check If Key Exists in Dictionary in Python? – Definitive Guide

Stack Vidhya

Python Dictionaries are used to store data in a key-value pair. Dictionaries are changeable and it doesn’t allow duplicate keys.

You can check if a key exists in a dictionary using dict.keys() method in Python.

In this tutorial, you’ll learn the different methods available to check if keys exist in a dictionary, and also you’ll learn how to check the keys in different use cases.

Sample Dictionary

This is the sample dictionary you’ll use in this tutorial. It contains the keys one, two, three, four.

All the keys are in lower case. This is useful for learning how to check if a key exists in the dictionary in a case-sensitive way.

There are three methods available in python to check if a key exists in the dictionary.

Using Keys()

You can check if a key exists in a dictionary using the keys() method and IN operator.

The keys() method will return a list of keys available in the dictionary and IF , IN statement will check if the passed key is available in the list.

If the key exists, it returns True else, it returns False .

key="one" if key in mydict.keys(): print("Key exists") else: print("Key does not exist")

This is how you can check if a key exists using the dictionary.keys() method.

Using If and In

You can check if the key exists in the dictionary using IF and IN. When using the dictionary directly with IF and IN, it’ll check if the key exists in the dictionary.

If a key exists, It returns True else it returns False .

key="one" if key in mydict: print("Key exists") else: print("Key does not exist")

This is how you can check if a key is available in the dictionary using the IF and IN .

Using has_key()

You can use the has_key() method to check if a key is available in a dictionary.

This is deprecated in python 3. If you are using an older version of python than python 3, then you can use this method.

You can check the python version in cmd using the below command.

import sys print(sys.version)
3.9.2 (default, Sep 4 2020, 00:03:40) [MSC v.1916 32 bit (Intel)]
if mydict.has_key("One"): print("Key exists") else: print("Key does not exist")

This tutorial uses the version Python 3. Hence, the below error is thrown as output.

 --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in ----> 1 if mydict.has_key("One"): 2 print("Key exists") 3 else: 4 print("Key does not exist") AttributeError: 'dict' object has no attribute 'has_key'

These are the different methods available in python to check if keys are available in the dictionary.

Now, you’ll learn about the different ways to use this.

Check If Multiple Keys Exists in Dictionary

You can check if multiple keys exist in the dictionary in one statement. You can use the all() along with the list comprehension to check if multiple or all keys exists in the dictionary.

if all (key in mydict for key in ("one","two")): print("All Keys exists in the dictionary") else: print("All doesn't exist")
  • for key in («one»,»two») – Keys to check in the dictionary will be iterated
  • key in mydict – During the each iteration of the for loop, each key will be checked if it exists in the mydict
  • Then, it’ll return a list which contains True or False based on the IN check.
  • At-last, the all() method checks the list. If it contains only True , then it means all the passed keys are available in the dictionary. If it contains at-least one False , then it returns false.
 All Keys exists in the dictionary

To check the negative scenario where all the passed keys are not available in the dictionary.

if all (key in mydict for key in ("one","two", "Five")): print("All Keys exists in the dictionary") else: print("All Keys doesn't exist")

This is how you can check if multiple keys exist in a dictionary in one statement.

Check If Key Exists in Dictionary Case Insensitive

By default, the IF , IN method is case-sensitive. When you check if a key exists in the dictionary using the IF , IN method, you should pass the proper case.

  • To check if a key exists in a dictionary in a case-insensitive way, you need to create a set by converting all the keys to either lowercase or uppercase.
  • convert all the keys to lowercase using the lower() method.
  • convert the key to be checked to lower case.
  • Pass the key to be checked and the set with lower case keys to IF , IN statement to check if a key exists in a case-insensitive way.
mydict = < "one": "1", "two": "2", "three": "3", "four": "4", >set_with_keys = set(key.lower() for key in mydict) key_to_check = "One" if key_to_check.lower() in set_with_keys: print("Key exists") else: print("Key doesn't exists")

This is how you can check if a key exists in a dictionary in a case-insensitive way.

Check If Key Exists and Has Value

You can check if a key exists and has a specific value in the dictionary by using the dictionary.items() method.

The items() method will return a list of tuples with the available key pairs in the dictionary.

Use IF and IN with a tuple to check if it exists in the dictionary, as shown below.

if ("one", "1") in mydict.items(): print("Key and Value exists") else: print("Key value pair doesn't exists")

This is how you can check if a key exists and has a value in the dictionary.

Check if Key Exists in Dictionary Time complexity

This section explains the time complexity of the different methods that checks if a key exists in a dictionary.

Time Complexity Table

Operation Average Case Amortized Worst Case
k in d O(1) O(n)
Get Item O(1) O(n)
Iteration[3] O(n) O(n)

Based on the above table, using the IF and IN statements are the best and fastest way to check if a key exists in the dictionary.

Additional Resources

Источник

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