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 Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read