Create Nested Dictionary using given List - Python
Last Updated :
04 Feb, 2025
The task of creating a nested dictionary in Python involves pairing the elements of a list with the key-value pairs from a dictionary. Each key from the list will map to a dictionary containing a corresponding key-value pair from the original dictionary. For example, given the dictionary a = {'Gfg': 4, 'is': 5, 'best': 9} and the list b = [8, 3, 2], the task is to create a nested dictionary like this:{8: {'Gfg': 4}, 3: {'is': 5}, 2: {'best': 9}} .
Using zip()
zip() pair elements from two or more iterables. In this case, it pairs the elements of the list with the key-value pairs from the dictionary. After pairing the elements, We can create a nested dictionary by iterating over the zipped pairs.
Python
a = {'Gfg': 4, 'is': 5, 'best': 9}
b = [8, 3, 2]
res = {key: {k: v} for key, (k, v) in zip(b, a.items())}
print(res)
Output{8: {'Gfg': 4}, 3: {'is': 5}, 2: {'best': 9}}
Explanation: zip(b, a.items()) pairs each element of b with a key-value pair from a, assigning the list element to key and the dictionary pair to (k, v). The comprehension {key: {k: v}} then creates a nested dictionary where each key from b maps to its corresponding {k: v} from a.
Using for loop
This method also uses the zip() function, but the key difference is that the looping process is slightly more explicit and manual. Here, we directly iterate over the zipped elements without using dictionary comprehension.
Python
a = {'Gfg': 4, 'is': 5, 'best': 9}
b = [8, 3, 2]
res = {}
for key, (k, v) in zip(b, a.items()):
res[key] = {k: v}
print(res)
Output{8: {'Gfg': 4}, 3: {'is': 5}, 2: {'best': 9}}
Explanation: for loop uses zip(b, a.items()) to pair each element from b with a key-value pair from a. For each pair, res[key] = {k: v} assigns a nested dictionary {k: v} to key, creating res where each key from b maps to the corresponding key-value pair from a.
Using dict()
While this method uses zip() to pair the list and dictionary items, it applies the dict() constructor to explicitly create the final nested dictionary. In this case, the dict() constructor is used with a lambda function to wrap each value in another dictionary.
Python
a = {'Gfg': 4, 'is': 5, 'best': 9}
b = [8, 3, 2]
res = dict(map(lambda key_val: (key_val[0], {key_val[1][0]: key_val[1][1]}), zip(b, a.items())))
print(res)
Output{8: {'Gfg': 4}, 3: {'is': 5}, 2: {'best': 9}}
Explanation: zip(b, a.items()) to pair elements from b with key-value pairs from a. The map with lambda creates tuples where each element from b is a key, and its value is a nested dictionary from a. dict() then converts these tuples into the final dictionary res.
Similar Reads
Convert Nested Dictionary to List in Python In this article, weâll explore several methods to Convert Nested Dictionaries to a List in Python. List comprehension is the fastest and most concise way to convert a nested dictionary into a list.Pythona = { "a": {"x": 1, "y": 2}, "b": {"x": 3, "y": 4}, } # Convert nested dictionary to a list of li
3 min read
Python - Create a Dictionary using List with None Values The task of creating a dictionary from a list of keys in Python involves transforming a list of elements into a dictionary where each element becomes a key. Each key is typically assigned a default value, such as None, which can be updated later. For example, if we have a list like ["A", "B", "C"],
3 min read
Load CSV data into List and Dictionary using Python Prerequisites: Working with csv files in Python CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or m
2 min read
Python Create Dictionary with Integer The task of creating a dictionary from a list of keys in Python, where each key is assigned a unique integer value, involves transforming the list into a dictionary. Each element in the list becomes a key and the corresponding value is typically its index or a different integer. For example, if we h
3 min read
Convert Dictionary to String List in Python The task of converting a dictionary to a string list in Python involves transforming the key-value pairs of the dictionary into a formatted string and storing those strings in a list. For example, consider a dictionary d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}. Converting this to a st
3 min read
How to Create List of Dictionary in Python Using For Loop The task of creating a list of dictionaries in Python using a for loop involves iterating over a sequence of values and constructing a dictionary in each iteration. By using a for loop, we can assign values to keys dynamically and append the dictionaries to a list. For example, with a list of keys a
3 min read
Create Dictionary from the List-Python The task of creating a dictionary from a list in Python involves mapping each element to a uniquely generated key, enabling structured data storage and quick lookups. For example, given a = ["gfg", "is", "best"] and prefix k = "def_key_", the goal is to generate {'def_key_gfg': 'gfg', 'def_key_is':
3 min read
Create Dynamic Dictionary using for Loop-Python The task of creating a dynamic dictionary using a for loop in Python involves iterating through a list of keys and assigning corresponding values dynamically. This method allows for flexibility in generating dictionaries where key-value pairs are added based on specific conditions or inputs during i
3 min read
Create Dynamic Dictionary in Python Creating a Dynamic Dictionary in Python is important in programming skills. By understanding how to generate dictionaries dynamically, programmers can efficiently adapt to changing data requirements, facilitating flexible and responsive code development. In this article, we will explore different me
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