Как найти слово в словаре python

I’m new to Python dictionaries. I’m making a simple program that has a dictionary that includes four names as keys and the respective ages as values. What I’m trying to do is that if the user enters the a name, the program checks if it’s in the dictionary and if it is, it should show the information about that name.

This is what I have so far:

def main():
    people = {
        "Austin" : 25,
        "Martin" : 30,
        "Fred" : 21,
        "Saul" : 50,
    }

    entry = input("Write the name of the person whose age you'd like to know, or write 'ALL' to see all names and ages: ")
    if entry == "ALL":
        for key, value in people.items():
            print ("Name: " + key)
            print ("Age: " + str(value) + "n")
    elif people.insert(entry) == True:
                print ("It works")

main()

I tried searching through the dictionary using .index() as I know it’s used in lists but it didn’t work. I also tried checking this post but I didn’t find it useful.

I need to know if there is any function that can do this.

In this Python tutorial, we will study the implementation of Python Dictionary Search by value. Here we will see how to search for a value in Dictionary using some examples in python.

In Python, dictionaries are built-in data structure that stores key-value pairs. The keys in a dictionary must be unique, while the values can be of any data type.

There are a few different ways to get the key by value in a Python dictionary, depending on your specific use case.

  • Using the items()method
  • Using the list comprehension
  • Using the index() method
  • Using the filter() and lambda function

Method-1: Using the items() method

To get the key by value in a python dictionary is using the items() method and a for loop, items() method returns a view object that contains the key-value pairs of the dictionary, as tuples in a list.

# This code creates a dictionary called "countries" that contains the keys "USA", "Germany", and "France" 
# and the respective values 56, 25, and 78.
countries = {'USA': 56, 'Germany': 25,'France':78}

# The for loop iterates through the items in the dictionary, where "key" represents the key of each item 
# and "value" represents the value of each item.
for key, value in countries.items():
    # The if statement checks if the value of each item is equal to 56.
    if value == 56:
        # If the value is equal to 56, the key of that item is printed.
        print(key)

The above code outputs the USA as it is the key which has a value of 56.

Python Dictionary Search by value using items()
Python Dictionary Search by value using items()

Read: Python dictionary key error

Method 2: Using the list comprehension

This method iterates over the key-value pairs in the dictionary and uses a list comprehension to find the first key whose associated value is equal to the value you’re looking for.

# This code creates a dictionary called "my_dictionary" that contains keys and values 
# representing countries and their respective values.
my_dictionary = {'Newzealand': 567,
            'United Kingdom' : 456,
            'China': 945,
            'Japan': 845
            }
# The variable new_val is set to 456
new_val = 456
# A list comprehension is used to iterate through the items in the dictionary and check if the value of each item is equal to new_val.
# If the value is equal to new_val, the key of that item is added to the list.
result=[new_k for new_k in my_dictionary.items() if new_k[1] == new_val][0][0]
# The result is printed
print(result)

The code outputs “United Kingdom” as it is the key which have value 456.

Python Dictionary Search by value using list comprehension
Python Dictionary Search by value using list comprehension.

Read: Python Dictionary Count + Examples

Method-3: Using the index() method

The index() method is a built-in method in Python that is used to find the index of an element in a list. It takes a single argument, which is the element you want to find the index of and returns the index of the first occurrence of that element in the list.

# This code creates a dictionary called "my_dictionary" that contains keys and values 
# representing countries and their respective values.
my_dictionary = {'Newzealand': 567,
            'United Kingdom' : 456,
            'China': 945,
            'Japan': 845
            }

# Get the values from the dictionary as a list
values = list(my_dictionary.values())

# The variable new_val is set to 456
new_val = 456

# Find the index of the value in the list
index = values.index(new_val)

# Get the key from the dictionary using the index
result = list(my_dictionary.keys())[index]

# The result is printed
print(result)

The above code outputs “United Kingdom” as it is the key which has value 456 but uses the index() method of the list.

Python Dictionary Search by value using index() method.jpg
Python Dictionary Search by value using index() method.jpg

Read: Python Dictionary duplicate keys

Method-4: Using the filter() and lambda function

The lambda function is a small anonymous function that can be used to perform a certain operation, and the filter() function is used to filter a sequence of elements based on a certain condition.

# my_dictionary is a dictionary that contains keys as countries and values as their population
my_dictionary = {'Newzealand': 567,
            'United Kingdom' : 456,
            'China': 945,
            'Japan': 845
            }

# new_val is the population value for which we want to find the corresponding country
new_val = 456

# Using lambda and filter() functions to filter the items of the dictionary
# and only the items with the value of new_val are returned
result = list(filter(lambda x: x[1] == new_val, my_dictionary.items()))[0][0]

# The result is printed
print(result)

The above code outputs “United Kingdom” as it is the key that has value 456 but uses the filter() and lambda function.

Python Dictionary Search by value using filter and lambda function
Python Dictionary Search by value using filter and lambda function

You may also like to read the following Python tutorials.

  • Python Dictionary of sets
  • Python dictionary contains + examples
  • Python convert dictionary to list
  • Python dictionary filter + Examples

In this Python tutorial, we have covered how to get a key using the value of the dictionary by following the below methods.

  • Python Dictionary Search by value using the items() method
  • Python Dictionary Search by value using the list comprehension
  • Python Dictionary Search by value using the index() method
  • Python Dictionary Search by value using the filter() and lambda function

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

I am a bit late, but another way is to use list comprehension and the any function, that takes an iterable and returns True whenever one element is True :

# Checking if string 'Mary' exists in the lists of the dictionary values
print any(any('Mary' in s for s in subList) for subList in myDict.values())

If you wanna count the number of element that have “Mary” in them, you can use sum():

# Number of sublists containing 'Mary'
print sum(any('Mary' in s for s in subList) for subList in myDict.values())

# Number of strings containing 'Mary'
print sum(sum('Mary' in s for s in subList) for subList in myDict.values())

From these methods, we can easily make functions to check which are the keys or values matching.

To get the keys containing ‘Mary’:

def matchingKeys(dictionary, searchString):
    return [key for key,val in dictionary.items() if any(searchString in s for s in val)]

To get the sublists:

def matchingValues(dictionary, searchString):
    return [val for val in dictionary.values() if any(searchString in s for s in val)]

To get the strings:

def matchingValues(dictionary, searchString):
    return [s for s i for val in dictionary.values() if any(searchString in s for s in val)]

To get both:

def matchingElements(dictionary, searchString):
    return {key:val for key,val in dictionary.items() if any(searchString in s for s in val)}

And if you want to get only the strings containing “Mary”, you can do a double list comprehension :

def matchingStrings(dictionary, searchString):
    return [s for val in dictionary.values() for s in val if searchString in s]

In this tutorial, you’ll learn how to use Python to check if a key exists in a dictionary. You’ll also learn how to check if a value exists in a dictionary. You’ll learn how to do this using the in operator, the .get() method, the has_key() function, and the .keys() and .values() methods.

Knowing how to work with Python dictionaries is an important skill. This can be especially helpful when working with web APIs that return JSON data.

While we can easily index a dictionary, if a key doesn’t exist, a KeyError will be thrown. This will cause some significant problems in your program, unless these errors are handled.

A much more safe alternative to using dictionary indexing, is to first check if a given key exists in a dictionary. Let’s get started learning!

The Quick Answer: Use in to see if a key exists

Quick Answer - Python Check if Key Exists in a Dictionary

What is a Python Dictionary?

Dictionaries in Python are one of the main, built-in data structures. They consist of key:value pairs that make finding an items value easy, if you know their corresponding key. One of the unique attributes of a dictionary is that keys must be unique, but that values can be duplicated.

Let’s take a look at how dictionaries look in Python. They’re created using {} curly brackets and the key:value pairs are separated by commas.

Let’s create a dictionary called ages, which, well, contains the ages of different people:

ages = {
    'Matt': 30,
    'Katie': 29,
    'Nik': 31,
    'Jack': 43,
    'Alison': 32,
    'Kevin': 38
}

One way that you’re often taught to access a dictionary value is to use indexing via the [] square bracket accessing. In the next section, you’ll see how dictionary indexing works and why it’s not always the best option. Following that, you’ll learn different methods of ensuring that a key exists.

The Problem with Indexing a Python Dictionary

Indexing a dictionary is an easy way of getting a dictionary key’s value – if the given key exists in the dictionary. Let’s take a look at how dictionary indexing works. We’ll use dictionary indexing to get the value for the key Nik from our dictionary ages:

>>> ages = {'Matt': 30, 'Katie': 29, 'Nik': 31, 'Jack': 43, 'Alison': 32, 'Kevin': 38}
>>> print(ages['Nik'])

31

We can see here that this worked beautifully. That being said, let’s see if we try to get the value for the key Jill, which doesn’t exist in the dictionary:

>>> ages = {'Matt': 30, 'Katie': 29, 'Nik': 31, 'Jack': 43, 'Alison': 32, 'Kevin': 38}
>>> print(ages['Jill'])

KeyError: 'Jill'

We can see here, that if we try to access a dictionary’s value for a key that doesn’t exist, that a KeyError is thrown. This has some huge implications for your code. Unless the error is explicitly handled, the program will fail. One way to avoid a KeyError is to ensure that a key actually exists in a Python dictionary.

That’s exactly what you’ll learn in the next few sections. Let’s get started!

Use Python to Check if a Key Exists: Python keys Method

Python dictionary come with a built-in method that allows us to generate a list-like object that contains all the keys in a dictionary. Conveniently, this is named the .keys() method.

Printing out dict.keys() looks like this:

print(ages.keys())
# Returns: dict_keys(['Matt', 'Katie', 'Nik', 'Jack', 'Alison', 'Kevin'])

We can see how that looks like a little bit like a list. We can now check if a key exists in that list-like object!

Let’s see how we can use the .keys() method to see if a key exists in a dictionary. Let’s use this method to see if a key exists:

# Check if a key exists in a Python dictionary by checking all keys
ages = {'Matt': 30, 'Katie': 29, 'Nik': 31, 'Jack': 43, 'Alison': 32, 'Kevin': 38}

some_key = 'James'
if some_key in ages.keys():
    print('Key exists')
else:
    print('Key doesn't exist')

# Returns Key doesn't exist

We can see here that we check whether or not a provided key, some_key, exists in the keys of our dictionary. In this case, the key didn’t exist and the program printed out Key doesn't exist.

In the next section, you’ll learn how to simplify this even further!

Use Python to Check if a Key Exists: Python in Operator

The method above works well, but we can simplify checking if a given key exists in a Python dictionary even further. We can actually omit the .keys() method entirely, and using the in operator will scan all keys in a dictionary.

Let’s see how this works in practise:

ages = {'Matt': 30, 'Katie': 29, 'Nik': 31, 'Jack': 43, 'Alison': 32, 'Kevin': 38}

some_key = 'Nik'
if some_key in ages:
    print('Key exists')
else:
    print('Key doesn't exist')

# Returns: Key exists

We can see here that our method actually looks very similar to the above, but we’ve been able to strip out the .keys() method entirely! This actually helps the code read a bit more plain-language.

in the next section, you’ll learn how to actually retrieve a key’s value, even if a key doesn’t exist!

Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

Use the .get Method to Check if a Key Exists in a Python Dictionary

Working with dictionaries in Python generally involves getting a key’s value – not just checking if it exists. You learned earlier that simply indexing the dictionary will throw a KeyError if a key doesn’t exist. How can we do this safely, without breaking out program?

The answer to this, is to use the Python .get() method. The .get() method will simply return None if a key doesn’t exist. Let’s try this out:

ages = {'Matt': 30, 'Katie': 29, 'Nik': 31, 'Jack': 43, 'Alison': 32, 'Kevin': 38}

print(ages.get('Jack'))
print(ages.get('Jill'))

# Returns:
# 43
# None

We can see here that when the .get() method is applied to return a key that exists, that key’s value is correctly returned. When a key doesn’t exist, the program continues to run, but it returns None.

What is particularly helpful about the Python .get() method, is that it allows us to return a value, even if a key doesn’t exist.

Say we wanted our program to notify us that a key didn’t exist. We could ask the .get() method to return “Key doesn’t exist!”.

Let’s see how we can do this:

ages = {'Matt': 30, 'Katie': 29, 'Nik': 31, 'Jack': 43, 'Alison': 32, 'Kevin': 38}

print(ages.get('Jill', "The key doesn't exist"))

# Returns: "The key doesn't exist!"

The .get() method is a great and safe way to see if a key exists in a Python dictionary. Now, let’s learn to see whether or not a given value exists in a Python dictionary.

Similar to the Python dictionary .keys() method, dictionaries have a corresponding .values() method, which returns a list-like object for all the values in a dictionary.

Let’s see how we can access all of a dictionary’s values:

ages = {'Matt': 30, 'Katie': 29, 'Nik': 31, 'Jack': 43, 'Alison': 32, 'Kevin': 38}

print(ages.values())
#Returns: dict_values([30, 29, 31, 43, 32, 38])

We can use this to see whether or not a value exists. Say we wanted to know if the age 27 existed in our dictionary, we could write the following:

ages = {'Matt': 30, 'Katie': 29, 'Nik': 31, 'Jack': 43, 'Alison': 32, 'Kevin': 38}

some_age = 27

if some_age in ages.values():
    print('Age exists!')
else:
    print("Age doesn't exist!")

# Returns: Age doesn't exist!

Now, what if we wanted to return the key or keys for a given value. We can safely do this using a list comprehension, which will have three permutations:

  1. Be an empty list, if the value doesn’t exist,
  2. Have one item, if the value exists once
  3. Have more than one item, if the value exists more than once

Let’s use a slightly modified dictionary to see this in action:

# Getting all keys of a certain value in a Python dictionary
ages = {'Matt': 30, 'Katie': 29, 'Nik': 31, 'Jack': 43, 'Jill': 43, 'Alison': 32, 'Kevin': 38}

value_43 = [key for key, value in ages.items() if value == 43]

print(value_43)

# Returns: ['Jack', 'Jill']

We’ve created a list comprehension that adds each key, if the value of that key is equal to 43.

What are Python List Comprehensions? To learn more about list comprehensions, check out my comprehensive tutorial here and my in-depth video below!

Conclusion

In this post, you learned how to check if a key exists in a Python dictionary. You learned how to do this with the .keys() method, the in operator, and the .get() method. You also learned how to see if a given value exists in a Python dictionary and how to get that values’ key(s).

To learn more about dictionaries in Python, check out the official documentation here.

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

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

Простое решение — использовать выражение генератора. Это приведет к простому коду ниже:

if __name__ == ‘__main__’:

    dicts = [

        {“lang”: “Java”, “version”: “14”},

        {“lang”: “Python”, “version”: “3.8”},

        {“lang”: “C++”, “version”: “17”},

    ]

    key = “lang”

    val = “Python”

    d = next((d for d in dicts if d.get(key) == val), None)

    print(d)        # {‘lang’: ‘Python’, ‘version’: ‘3.8’}

Скачать  Выполнить код

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

Другой способ поиска в списке словарей — использование filter() функция в Python 3.

if __name__ == ‘__main__’:

    dicts = [

        {“lang”: “Java”, “version”: “14”},

        {“lang”: “Python”, “version”: “3.8”},

        {“lang”: “C++”, “version”: “17”},

    ]

    key = “lang”

    val = “Python”

    d = next(filter(lambda d: d.get(key) == val, dicts), None)

    print(d)        # {‘lang’: ‘Python’, ‘version’: ‘3.8’}

Скачать  Выполнить код

Это все о поиске значения в списке словарей в Python.

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

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

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

Добавить комментарий