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 = { "hello": 56, "at" : 23 , "test" : 43, "this" : 97, "here" : 43, "now" : 97 }
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.
here test
Now let’s see how to get the list of keys by given value
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)
Output:
here test
Same can be achieved by List Comprehensions i.e.
''' Get list of keys with value 43 using list comprehension ''' listOfKeys = [key for (key, value) in dictOfWords.items() if value == 43]
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.
[43, 97]
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)
Output:
Keys with value equal to any one from the list [43, 97] this here now test
Python Dictionary Tutorial - Series:
- What is a Dictionary in Python & why do we need it?
- Creating Dictionaries in Python
- Iterating over dictionaries
- Check if a key exists in dictionary
- Check if a value exists in dictionary
- Get all the keys in Dictionary
- Get all the Values in a Dictionary
- Remove a key from Dictionary
- Add key/value pairs in Dictionary
- Find keys by value in Dictionary
- Filter a dictionary by conditions
- Print dictionary line by line
- Convert a list to dictionary
- Sort a Dictionary by key
- Sort a dictionary by value in descending or ascending order
- Dictionary: Shallow vs Deep Copy
- Remove keys while Iterating
- Get all keys with maximum value
- 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 = [key for (key, value) in dictOfWords.items() if value == 43] #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()
Output:
Original Dictionary {'hello': 56, 'at': 23, 'this': 97, 'here': 43, 'test': 43, 'now': 97} 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
Pandas Tutorials -Learn Data Analysis with Python
-
Pandas Tutorial Part #1 - Introduction to Data Analysis with Python
-
Pandas Tutorial Part #2 - Basics of Pandas Series
-
Pandas Tutorial Part #3 - Get & Set Series values
-
Pandas Tutorial Part #4 - Attributes & methods of Pandas Series
-
Pandas Tutorial Part #5 - Add or Remove Pandas Series elements
-
Pandas Tutorial Part #6 - Introduction to DataFrame
-
Pandas Tutorial Part #7 - DataFrame.loc[] - Select Rows / Columns by Indexing
-
Pandas Tutorial Part #8 - DataFrame.iloc[] - Select Rows / Columns by Label Names
-
Pandas Tutorial Part #9 - Filter DataFrame Rows
-
Pandas Tutorial Part #10 - Add/Remove DataFrame Rows & Columns
-
Pandas Tutorial Part #11 - DataFrame attributes & methods
-
Pandas Tutorial Part #12 - Handling Missing Data or NaN values
-
Pandas Tutorial Part #13 - Iterate over Rows & Columns of DataFrame
-
Pandas Tutorial Part #14 - Sorting DataFrame by Rows or Columns
-
Pandas Tutorial Part #15 - Merging or Concatenating DataFrames
-
Pandas Tutorial Part #16 - DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.