Python - Assign values to Values List
Last Updated :
13 Apr, 2023
Given 2 dictionaries, assign values to value list elements mapping from dictionary 2.
Input : test_dict = {'Gfg' : [3, 6], 'best' :[9]}, look_dict = {3 : [1, 5], 6 : "Best", 9 : 12} Output : {'Gfg': {3: [1, 5], 6: 'Best'}, 'best': {9: 12}} Explanation : 3 is replaced by key 3 and value [1, 5] and so on. Input : test_dict = {'Gfg' : [3, 6]}, look_dict = {3 : [1, 5], 6 : "Best"} Output : {'Gfg': {3: [1, 5], 6: 'Best'}} Explanation : 3 is replaced by key 3 and value [1, 5] and so on.
Method #1 : Using nested dictionary comprehension
In this, we use inner dictionary comprehension to map values elements to dict 2, and outer dict is used to extract all keys from dictionary 1.
Python3
# Python3 code to demonstrate working of
# Assign values to Values List
# Using nested dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : [3, 6],
'is' : [4, 2],
'best' :[9]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing lookup dict
look_dict = {3 : [1, 5], 6 : "Best", 4 : 10, 9 : 12, 2 : "CS"}
# nested dictionaries to sought solution
res = {idx: {ikey: look_dict[ikey] for ikey in test_dict[idx]} for idx in test_dict}
# printing result
print("The mapped dictionary : " + str(res))
OutputThe original dictionary is : {'Gfg': [3, 6], 'is': [4, 2], 'best': [9]}
The mapped dictionary : {'Gfg': {3: [1, 5], 6: 'Best'}, 'is': {4: 10, 2: 'CS'}, 'best': {9: 12}}
Time Complexity: O(N*M), where N is the number of key-value pairs in the test_dict and M is number of values in any value list.
Auxiliary space: O(N + K), where N is the number of key-value pairs in the test_dict and K is the number of keys in the look_dict.
Method #2 : Using items() + dictionary comprehension
Similar to above method, another one-liner, difference being that items() is used for element access.
Python3
# Python3 code to demonstrate working of
# Assign values to Values List
# Using items() + dictionary comprehension
# initializing dictionary
test_dict = {'Gfg': [3, 6],
'is': [4, 2],
'best': [9]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing lookup dict
look_dict = {3: [1, 5], 6: "Best", 4: 10, 9: 12, 2: "CS"}
# nested dictionaries to sought solution
# items() used to access key-val pairs
res = {key: {ikey: ival for (ikey, ival) in look_dict.items(
) if ikey in val} for (key, val) in test_dict.items()}
# printing result
print("The mapped dictionary : " + str(res))
OutputThe original dictionary is : {'Gfg': [3, 6], 'is': [4, 2], 'best': [9]}
The mapped dictionary : {'Gfg': {3: [1, 5], 6: 'Best'}, 'is': {4: 10, 2: 'CS'}, 'best': {9: 12}}
Method#3: Using for loop
Approach
this approach uses dictionary comprehension to create a new dictionary with values assigned based on the look_dict.
Algorithm
1. Create a set of all the values in the look_dict.
2. Iterate over each key-value pair in the test_dict.
3. Create a new dictionary with the same keys as the test_dict and an empty dictionary as the value.
Iterate over each value in the value list of the current key.
4. If the value is present in the set of values from the look_dict, then add a key-value pair to the value dictionary with the key as the value and the value as the corresponding value from the look_dict.
5. Return the new dictionary.
Python3
def assign_values(test_dict, look_dict):
values_set = set(look_dict.keys())
new_dict = {key: {} for key in test_dict}
for key, values in test_dict.items():
for value in values:
if value in values_set:
new_dict[key][value] = look_dict[value]
return new_dict
test_dict = {'Gfg' : [3, 6],
'is' : [4, 2],
'best' :[9]}
look_dict = {3 : [1, 5], 6 : "Best", 4 : 10, 9 : 12, 2 : "CS"}
print(assign_values(test_dict, look_dict))
Output{'Gfg': {3: [1, 5], 6: 'Best'}, 'is': {4: 10, 2: 'CS'}, 'best': {9: 12}}
Time Complexity: O(NM), where N is the number of key-value pairs in the test_dict and M is the maximum number of values in any value list.
Space Complexity: O(N + K), where N is the number of key-value pairs in the test_dict and K is the number of keys in the look_dict.
Method #4: Using defaultdict and for loop
- Import the defaultdict module from the collections library.
- Create a dictionary called test_dict that contains the original dictionary data.
- Create a dictionary called look_dict that contains the lookup data.
- Create an empty defaultdict called res to store the result.
- Iterate through each key-value pair in test_dict using the items() method.
- For each key-value pair, iterate through the values using a for loop.
- For each value, use it as a key to look up the corresponding value in look_dict.
- Add a new key-value pair to the corresponding dictionary in res, where the key is the current value and the value is the value from look_dict that was looked up in the previous step.
- Repeat steps 6-8 for all values in the current key-value pair.
- Repeat steps 5-9 for all key-value pairs in test_dict.
- Print the resulting res
Python3
from collections import defaultdict
# initializing dictionary
test_dict = {'Gfg' : [3, 6],
'is' : [4, 2],
'best' :[9]}
# initializing lookup dict
look_dict = {3 : [1, 5], 6 : "Best", 4 : 10, 9 : 12, 2 : "CS"}
# creating a defaultdict to store the result
res = defaultdict(dict)
# iterating through the test_dict and its values
for key, values in test_dict.items():
# iterating through the values
for value in values:
# using the value to lookup the corresponding values in the look_dict
res[key][value] = look_dict[value]
# printing result
print("The mapped dictionary : " + str(res))
OutputThe mapped dictionary : defaultdict(<class 'dict'>, {'Gfg': {3: [1, 5], 6: 'Best'}, 'is': {4: 10, 2: 'CS'}, 'best': {9: 12}})
Time complexity: O(NM), where N is the number of keys in the test_dict and M is the average number of values per key.
Auxiliary space: O(NM), since we are storing the result in a dictionary.
Similar Reads
Python | Assign value to unique number in list We can assign all the numbers in a list a unique value that upon repetition it retains that value retained to it. This is a very common problem that is faced in web development when playing with id's. Let's discuss certain ways in which this problem can be solved. Method #1: Using enumerate() + list
7 min read
Assign Multiple Variables with List Values - Python We are given a list and our task is to assign its elements to multiple variables. For example, if we have a list a = [1, 2, 3], we can assign the elements of the list to variables x, y, z such that x = 1, y = 2, and z = 3. Below, we will explore different methods to assign list values to variables.U
3 min read
Python - Add Values to Dictionary of List A dictionary of lists allows storing grouped values under specific keys. For example, in a = {'x': [10, 20]}, the key 'x' maps to the list [10, 20]. To add values like 30 to this list, we use efficient methods to update the dictionary dynamically. Letâs look at some commonly used methods to efficien
3 min read
Unpack Whole List into Variables - Python The task of unpacking a list into variables in Python involves extracting elements from a list and assigning them to individual variables. For example, given the list x = [1, 3, 7, 4, 2], unpacking it into a, b, c, d, e assigns 1 to a, 3 to b, 7 to c, 4 to d, and 2 to e, allowing for easier access t
3 min read
Accessing index and value in Python list We are given a list, and our task is to access both the index and value of each element in the list using Python. For example, using enumerate(list) in a loop like for index, value in enumerate(list) allows us to access both the index and the value together.Using enumerate() enumerate() is preferred
2 min read
Python - Assign values to initialized dictionary keys Sometimes, while working with python dictionaries, we can have a problem in which we need to initialize dictionary keys with values. We save a mesh of keys to be initialized. This usually happens during web development while working with JSON data. Lets discuss certain ways in which this task can be
5 min read
Python Convert Dictionary to List of Values Python has different types of built-in data structures to manage your data. A list is a collection of ordered items, whereas a dictionary is a key-value pair data. Both of them are unique in their own way. In this article, the dictionary is converted into a list of values in Python using various con
3 min read
Python - Update values of a list of dictionaries The task of updating the values of a list of dictionaries in Python involves modifying specific keys or values within each dictionary in the list based on given criteria or conditions. This task is commonly encountered when working with structured data that needs transformation or enrichment.For exa
4 min read
Inverse Dictionary Values List - Python We are given a dictionary and the task is to create a new dictionary where each element of the value lists becomes a key and the original keys are grouped as lists of values for these new keys.For example: dict = {1: [2, 3], 2: [3], 3: [1]} then output will be {2: [1], 3: [1, 2], 1: [3]}Using defaul
2 min read
Python - Values Frequency Index List Sometimes, while working with Python tuples, we can have a problem in which we need to extract the frequency of each value in tuple. This has been solved earlier. We can have a modification in which we need to create list in which index represents the key and value of it represents the frequency of
4 min read