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
Assign Ids to Each Unique Value in a List - Python
The task of assigning unique IDs to each value in a list involves iterating over the elements and assigning a unique identifier to each distinct value. Since lists in Python are mutable, the goal is to efficiently assign an ID to each unique element while ensuring that repeated elements receive the
3 min read
How to Yield Values from List in Python
In Python, we often deal with large lists where processing all elements at once might be inefficient in terms of memory usage. The yield keyword allows us to create iterators that yield values one at a time, instead of storing them all in memory. In this article, we will explore different methods to
3 min read
Python - Group keys to values list
Sometimes, while working with Python dictionaries, we can have problem in which we need to find all possible values of all keys in a dictionary. This utility is quite common and can occur in many domains including day-day programming and school programming. Lets discuss certain way in which this tas
5 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
Get Python Dictionary Values as List - Python
We are given a dictionary where the values are lists and our task is to retrieve all the values as a single flattened list. For example, given the dictionary: d = {"a": [1, 2], "b": [3, 4], "c": [5]} the expected output is: [1, 2, 3, 4, 5]Using itertools.chain()itertools.chain() function efficiently
2 min read
Python - Values from custom List in Records
Sometimes, while working with Python records, we can have a problem in which we need to extract all the values from the custom list in list dictionary records. This problem can have applications in domains such as web development and school programming. Let's discuss certain ways in which this task
7 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