Open In App

Python – Keys associated with Values in Dictionary

Last Updated : 05 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 way in which this task can be performed.

Input : test_dict = {‘abc’ : [10, 30], ‘bcd’ : [30, 40, 10]} Output : {10: [‘abc’, ‘bcd’], 30: [‘abc’, ‘bcd’], 40: [‘bcd’]} Input : test_dict = {‘gfg’ : [1, 2, 3], ‘is’ : [1, 4], ‘best’ : [4, 2]} Output : {1: [‘is’, ‘gfg’], 2: [‘gfg’, ‘best’], 3: [‘gfg’], 4: [‘is’, ‘best’]}

Method : Using defaultdict() + loop The combination of above functionalities can solve this problem. In this, we create defaultdict of list and insert the element by checking the association inside the look using brute force approach. 

Python3




# Python3 code to demonstrate working of
# Values Associated Keys
# Using defaultdict() + loop
from collections import defaultdict
 
# initializing dictionary
test_dict = {'gfg' : [1, 2, 3], 'is' : [1, 4], 'best' : [4, 2]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Values Associated Keys
# Using defaultdict() + loop
res = defaultdict(list)
for key, val in test_dict.items():
    for ele in val:
        res[ele].append(key)
 
# printing result
print("The values associated dictionary : " + str(dict(res)))


Output : 

The original dictionary is : {'is': [1, 4], 'gfg': [1, 2, 3], 'best': [4, 2]}
The values associated dictionary : {1: ['is', 'gfg'], 2: ['gfg', 'best'], 3: ['gfg'], 4: ['is', 'best']}

 Method 2: Using dict comprehension + loop

  • Initialize an empty dictionary called result_dict.
  • Loop through the key-value pairs in the test_dict using the items() method.
  • For each key-value pair, loop through the values in the list and check if the value is already a key in result_dict.
  • If the value is already a key in result_dict, append the key of the current key-value pair to the list of values associated with the existing key.
  • If the value is not already a key in result_dict, add the value as a new key and initialize its value to be a list containing the key of the current key-value pair.
  • Print the resulting dictionary.

Python3




# Python3 code to demonstrate working of
# Assign values to initialized dictionary keys
 
# Python3 code to demonstrate working of
# Values Associated Keys
# Using dict comprehension + loop
 
# initializing dictionary
test_dict = {'gfg' : [1, 2, 3], 'is' : [1, 4], 'best' : [4, 2]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Values Associated Keys
# Using dict comprehension + loop
result_dict = {}
for key, val in test_dict.items():
    for ele in val:
        if ele in result_dict:
            result_dict[ele].append(key)
        else:
            result_dict[ele] = [key]
 
# printing result
print("The values associated dictionary : " + str(result_dict))


Output

The original dictionary is : {'gfg': [1, 2, 3], 'is': [1, 4], 'best': [4, 2]}
The values associated dictionary : {1: ['gfg', 'is'], 2: ['gfg', 'best'], 3: ['gfg'], 4: ['is', 'best']}

Time complexity: O(n^2), where n is the total number of values in all the lists in the test_dict. This is because we need to loop through all the values for each key in test_dict.

Auxiliary space: O(n), where n is the total number of values in all the lists in the test_dict. This is because we need to store the mapping from each value to its associated keys in the result_dict.

Method 3 : Using the setdefault() method of dictionary. 

Initialize an empty dictionary, result_dict, to store the values associated with keys.
Loop through the keys and values of the input dictionary, test_dict.
For each value, loop through its elements.
Use the setdefault() method to insert the element as a key in the result_dict if it is not already present, and assign an empty list as its value.
Append the key to the list of the element in the result_dict.
Print the result_dict.

Python3




# Python3 code to demonstrate working of
# Values Associated Keys
# Using setdefault()
 
# initializing dictionary
test_dict = {'gfg' : [1, 2, 3], 'is' : [1, 4], 'best' : [4, 2]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Values Associated Keys
# Using setdefault()
result_dict = {}
for key, val in test_dict.items():
    for ele in val:
        result_dict.setdefault(ele, []).append(key)
 
# printing result
print("The values associated dictionary : " + str(result_dict))


Output

The original dictionary is : {'gfg': [1, 2, 3], 'is': [1, 4], 'best': [4, 2]}
The values associated dictionary : {1: ['gfg', 'is'], 2: ['gfg', 'best'], 3: ['gfg'], 4: ['is', 'best']}

The time complexity of this approach is O(n * m), where n is the number of keys in the input dictionary and m is the average number of elements in the values.
The auxiliary space of this approach is O(n * m), where n is the number of unique elements in the values and m is the average number of keys associated with each element.
 



Similar Reads

Python - Keys associated with value list in dictionary
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,
4 min read
Python - Associated Values Frequencies in Dictionary
Sometimes, while working with dictionaries, we can have problem in which we need to compute the values associated to each value in dictionary in records list. This kind of problem is peculiar, but can have application in development domains. Lets discuss certain way in which this task can be performed. Counting Associated Values Frequencies in Dict
5 min read
Python - Append Dictionary Keys and Values ( In order ) in dictionary
Given a dictionary, perform append of keys followed by values in list. Input : test_dict = {"Gfg" : 1, "is" : 2, "Best" : 3} Output : ['Gfg', 'is', 'Best', 1, 2, 3] Explanation : All the keys before all the values in list. Input : test_dict = {"Gfg" : 1, "Best" : 3} Output : ['Gfg', 'Best', 1, 3] Explanation : All the keys before all the values in
5 min read
How to extract frequency associated with fft values in Python?
In this article, we will find out the extract the values of frequency from an FFT. We can obtain the magnitude of frequency from a set of complex numbers obtained after performing FFT i.e Fast Fourier Transform in Python. The frequency can be obtained by calculating the magnitude of the complex number. So simple ab(x) on each of those complex numbe
3 min read
Python - Extract selective keys' values Including Nested Keys
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys' values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records. This problem caters all the nestings for extraction of keys' values. Let's discuss certain w
7 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
Python | Split dictionary keys and values into separate lists
Given a dictionary, the task is to split a dictionary in python into keys and values into different lists. Let's discuss the different ways we can do this. Example Input: {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} Output: keys: ['a', 'b', 'c'] values: ['akshat', 'bhuvan', 'chandan']Method 1: Split dictionary keys and values using inbuilt functi
5 min read
Python program to Swap Keys and Values in Dictionary
Dictionary is quite a useful data structure in programming that is usually used to hash a particular key with value so that they can be retrieved efficiently. Let’s discuss various ways of swapping the keys and values in Python Dictionary. Method#1 (Does not work when there are multiple same values): One naive solution maybe something like just swa
4 min read
Python - Test if Values Sum is Greater than Keys Sum in dictionary
Given a Dictionary, check if the summation of values is greater than the keys sum. Input : test_dict = {5:3, 1:3, 10:4, 7:3, 8:1, 9:5} Output : False Explanation : Values sum = 19 < 40, which is key sum, i.e false.Input : test_dict = {5:3, 1:4} Output : True Explanation : Values sum = 7 > 6, which is key sum, i.e true. Method #1: Using loop I
8 min read
Practice Tags :
three90RightbarBannerImg