Python - Keys associated with value list in dictionary
Last Updated :
22 Aug, 2023
Sometimes, while working with Python dictionaries, we can have a problem finding the key of a particular value in the value list. This problem is quite common and can have applications in many domains. Let us discuss certain ways in which we can Get Keys associated with Values in the Dictionary in Python.
Example
Input: {'gfg': [4, 5], 'best': [10, 12], 'is': [8]} , list = [4,10]
Output: ['gfg', 'best']
Explanation: In this example, the keys associated with the value inside the list i.e. 4 and 10 is 'gfg' and 'best' respectively.
Get Keys Associated with Value List in Python
Below are the methods that we will cover in this article:
Keys associated with Value list using loop + items()
The combination of the above functions can be used to solve this problem. In this example, we extract all elements of the dictionary using Python items(), and a loop is used to compile the rest of the logic.
Python3
# initializing dictionary
test_dict = {'gfg' : [4, 5], 'is' : [8], 'best' : [10, 12]}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing value list
val_list = [5, 10]
# Value's Key association
# Using loop + items()
temp = {}
for key, vals in test_dict.items():
for val in vals:
temp[val] = key
res = [temp[ele] for ele in val_list]
# printing result
print("The keys mapped to " + str(val_list) + " are : " + str(res))
OutputThe original dictionary : {'gfg': [4, 5], 'is': [8], 'best': [10, 12]}
The keys mapped to [5, 10] are : ['gfg', 'best']
Keys associated with Value list using list comprehension + any()
This is yet another way in which this task can be performed. It offers shorthands that can be used to solve this problem. In this example, we use Python any() to compute if the key contains any of the values in the value list.
Python3
# initializing dictionary
test_dict = {'gfg' : [4, 5], 'is' : [8], 'best' : [10, 12]}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing value list
val_list = [5, 10]
# Value's Key association
# Using list comprehension + any()
res = [key for key, val in test_dict.items() if any(y in val for y in val_list)]
# printing result
print("The keys mapped to " + str(val_list) + " are : " + str(res))
OutputThe original dictionary : {'gfg': [4, 5], 'is': [8], 'best': [10, 12]}
The keys mapped to [5, 10] are : ['gfg', 'best']
Keys associated with Value list using filter() function
In this example, we are using filter() function to find the key associated with value list. Firstly, print the original dictionary after initializing the dictionary. Create the list of dictionary values to be searched. Create a function that returns True if any element from the input list is in the dictionary values. To filter out dictionary objects that meet the above requirement, use the filter() function. Using the dict.keys() method, extract the keys of the filtered dictionary entries and store them in a Python list. Print the final outcome.
Python3
# initializing dictionary
test_dict = {'gfg' : [4, 5], 'is' : [8], 'best' : [10, 12]}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing value list
val_list = [5, 10]
# Value's Key association
# Using filter()
def is_value_present(val_list):
def helper(lst):
return any(x in lst for x in val_list)
return helper
filtered_dict = dict(filter
(lambda x: is_value_present(val_list)(x[1]),
test_dict.items()))
# extracting keys of filtered dictionary items
res = list(filtered_dict.keys())
# printing result
print("The keys mapped to " + str(val_list) + " are : " + str(res))
OutputThe original dictionary : {'gfg': [4, 5], 'is': [8], 'best': [10, 12]}
The keys mapped to [5, 10] are : ['gfg', 'best']
Similar Reads
Python - Keys associated with Values in Dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to reform the dictionary, in the form in which all the values point to the keys that they belong to. This kind of problem can occur in many domains including web development and data domains. Lets discuss certain
5 min read
Dictionary with Tuple as Key in Python
Dictionaries allow a wide range of key types, including tuples. Tuples, being immutable, are suitable for use as dictionary keys when storing compound data. For example, we may want to map coordinates (x, y) to a specific value or track unique combinations of values. Let's explores multiple ways to
4 min read
Python - Unique value keys in a dictionary with lists as values
Sometimes, while working with Python dictionaries, we can have problem in which we need to extract keys with values that are unique (there should be at least one item not present in other lists), i.e doesn't occur in any other key's value lists. This can have applications in data preprocessing. Lets
4 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'c
7 min read
Add new keys to a dictionary in Python
In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples:Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=).Pythond = {"a": 1, "b": 2} d["c"] = 3 print(d)Output{'a': 1, 'b': 2, 'c': 3}
2 min read
How to Add Same Key Value in Dictionary Python
Dictionaries are powerful data structures that allow us to store key-value pairs. However, one common question that arises is how to handle the addition of values when the keys are the same. In this article, we will see different methods to add values for the same dictionary key using Python.Adding
2 min read
Python - Value List Key Flattening
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform pairing of each value of keys to extract the flattened dictionary. This kind of problem can have application in data domains. Lets discuss certain way in which this task can be performed. Method #1:
7 min read
How to use a List as a key of a Dictionary in Python 3?
In Python, we use dictionaries to check if an item is present or not . Dictionaries use key:value pair to search if a key is present or not and if the key is present what is its value . We can use integer, string, tuples as dictionary keys but cannot use list as a key of it . The reason is explained
3 min read
Get Key from Value in Dictionary - Python
The goal is to find the keys that correspond to a particular value. Since dictionaries quickly retrieve values based on keys, there isn't a direct way to look up a key from a value. Using next() with a Generator ExpressionThis is the most efficient when we only need the first matching key. This meth
5 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value c
5 min read