Python find in dictionary by value

Python : How to find keys by value in dictionary ?

In this article we will discuss how to find all keys associated with a given single value or multiple values.

Suppose we have a dictionary of words and thier frequency i.e.

# Dictionary of strings and int dictOfWords =

Now we want to get all the keys in dictionary whose value is 43. Like in our case there will two keys who has value 43 i.e.

Now let’s see how to get the list of keys by given value

Frequently Asked:

Find keys by value in dictionary

As, dict.items() returns an iterable sequence of all key value pairs in dictionary. So, we will iterate over this sequence and for each entry we will check if value is same as given value then we will add the key in a separate list i.e.

''' Get a list of keys from dictionary which has the given value ''' def getKeysByValue(dictOfElements, valueToFind): listOfKeys = list() listOfItems = dictOfElements.items() for item in listOfItems: if item[1] == valueToFind: listOfKeys.append(item[0]) return listOfKeys

Now let’s use this function to get keys by value 43 i.e.

''' Get list of keys with value 43 ''' listOfKeys = getKeysByValue(dictOfWords, 43) print("Keys with value equal to 43") #Iterate over the list of keys for key in listOfKeys: print(key)

Same can be achieved by List Comprehensions i.e.

''' Get list of keys with value 43 using list comprehension ''' listOfKeys = Python find in dictionary by value

Find keys in dictionary by value list

Suppose we want to find all the keys in dictionary whose value matches with any of the value given in list i.e.

To do that we will iterate over iterable sequence returned by dict.items() and for each entry we will check if its value matches with any entry from the given value list, if yes then we will add that key in a separate list i.e.

''' Get a list of keys from dictionary which has value that matches with any value in given list of values ''' def getKeysByValues(dictOfElements, listOfValues): listOfKeys = list() listOfItems = dictOfElements.items() for item in listOfItems: if item[1] in listOfValues: listOfKeys.append(item[0]) return listOfKeys

Now lets use this to find all the keys from dictionary whose values is equal to any value from the list i.e.

''' Get list of keys with any of the given values ''' listOfKeys = getKeysByValues(dictOfWords, [43, 97] ) #Iterate over the list of values for key in listOfKeys: print(key)
Keys with value equal to any one from the list [43, 97] this here now test

Python Dictionary Tutorial — Series:

  1. What is a Dictionary in Python & why do we need it?
  2. Creating Dictionaries in Python
  3. Iterating over dictionaries
  4. Check if a key exists in dictionary
  5. Check if a value exists in dictionary
  6. Get all the keys in Dictionary
  7. Get all the Values in a Dictionary
  8. Remove a key from Dictionary
  9. Add key/value pairs in Dictionary
  10. Find keys by value in Dictionary
  11. Filter a dictionary by conditions
  12. Print dictionary line by line
  13. Convert a list to dictionary
  14. Sort a Dictionary by key
  15. Sort a dictionary by value in descending or ascending order
  16. Dictionary: Shallow vs Deep Copy
  17. Remove keys while Iterating
  18. Get all keys with maximum value
  19. Merge two or more dictionaries in python

Subscribe with us to join a list of 2000+ programmers and get latest tips & tutorials at your inbox through our weekly newsletter.

Complete example is as follows,

''' Get a list of keys from dictionary which has the given value ''' def getKeysByValue(dictOfElements, valueToFind): listOfKeys = list() listOfItems = dictOfElements.items() for item in listOfItems: if item[1] == valueToFind: listOfKeys.append(item[0]) return listOfKeys ''' Get a list of keys from dictionary which has value that matches with any value in given list of values ''' def getKeysByValues(dictOfElements, listOfValues): listOfKeys = list() listOfItems = dictOfElements.items() for item in listOfItems: if item[1] in listOfValues: listOfKeys.append(item[0]) return listOfKeys def main(): # Dictionary of strings and int dictOfWords = < "hello": 56, "at" : 23 , "test" : 43, "this" : 97, "here" : 43, "now" : 97 >print("Original Dictionary") print(dictOfWords) ''' Get list of keys with value 43 ''' listOfKeys = getKeysByValue(dictOfWords, 43) print("Keys with value equal to 43") #Iterate over the list of keys for key in listOfKeys: print(key) print("Keys with value equal to 43") ''' Get list of keys with value 43 using list comprehension ''' listOfKeys = Python find in dictionary by value #Iterate over the list of keys for key in listOfKeys: print(key) print("Keys with value equal to any one from the list [43, 97] ") ''' Get list of keys with any of the given values ''' listOfKeys = getKeysByValues(dictOfWords, [43, 97] ) #Iterate over the list of values for key in listOfKeys: print(key) if __name__ == '__main__': main()
Original Dictionary Keys with value equal to 43 here test Keys with value equal to 43 here test Keys with value equal to any one from the list [43, 97] this here test now

Источник

Python Dictionary Search by value

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 = # 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()

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 = # 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

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 = # 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

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 = # 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

You may also like to read the following Python tutorials.

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

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Find Key by Value in Python Dictionary

Find Key by Value in Python Dictionary

  1. Use dict.items() to Find Key by Value in Python Dictionary
  2. Use .keys() and .values() to Find Key by Value in Python Dictionary

Dictionary is a collection of items in a key-value pair. Items stored in a dictionary are unordered. In this article, we will introduce different ways to find key by value in a Python dictionary. Usually, a value is accessed using a key, but here we will access a key using a value. Here the key is an identity associated with the value.

Use dict.items() to Find Key by Value in Python Dictionary

dict.items() method returns a list whose individual element is a tuple consisting of the key of the value of the dictionary. We can get the key by iterating the result of dict.items() and comparing the value with the second element of the tuple.

my_dict ="John":1, "Michael":2, "Shawn":3> def get_key(val):  for key, value in my_dict.items():  if val == value:  return key   return "There is no such Key"  print(get_key(1)) print(get_key(2)) 

Use .keys() and .values() to Find Key by Value in Python Dictionary

dict.keys() returns a list consisting keys of the dictionary; dict.values() returns a list consisting of values of the dictionary. The order of the items generated in .keys() and .values() are the same.

The index() method of the Python list gives the index of the given argument. We can pass the value to the index() method of the generated key list to get the index of this value. Then the key could be obtained by accessing the generated value list with the returned index.

my_dict ="John":1, "Michael":2, "Shawn":3>  list_of_key = list(my_dict.keys()) list_of_value = list(my_dict.values())  position = list_of_value.index(1) print(list_of_key[position])  position = list_of_value.index(2) print(list_of_key[position]) 

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

Related Article — Python Dictionary

Источник

Читайте также:  Https rusada triagonal net files rusada landing index html
Оцените статью