Write a Python program to convert a list into a nested dictionary of keys

Python: Convert a list into a nested dictionary of keys

Last update on April 27 2021 12:47:55 (UTC/GMT +8 hours)

Python – Convert Lists to Nested Dictionary

Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert list to nestings, i.e each list values representing new nested level. This kind of problem can have application in many domains including web development. Lets discuss certain way in which this task can be performed.

Method : Using zip() + list comprehension
The combination of above functions can be combined to perform this task. In this, we iterate for zipped list and render the nested dictionaries using list comprehension.




# Python3 code to demonstrate working of
# Convert Lists to Nestings Dictionary
# Using list comprehension + zip()
# initializing list
test_list1 = ["gfg", 'is', 'best']
test_list2 = ['ratings', 'price', 'score']
test_list3 = [5, 6, 7]
# printing original list
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
# Convert Lists to Nestings Dictionary
# Using list comprehension + zip()
res = [{a: {b: c}} for (a, b, c) in zip(test_list1, test_list2, test_list3)]
# printing result
print("The constructed dictionary : " + str(res))
Output : The original list 1 is : ['gfg', 'is', 'best'] The original list 2 is : ['ratings', 'price', 'score'] The original list 3 is : [5, 6, 7] The constructed dictionary : [{'gfg': {'ratings': 5}}, {'is': {'price': 6}}, {'best': {'score': 7}}]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Article Tags :
Python
Python list-programs
Python-nested-dictionary

What is Python Nested Dictionary?

A dictionary can contain another dictionary, which in turn can contain dictionaries themselves, and so on to arbitrary depth. This is known asnested dictionary.

Nested dictionaries are one of many ways to represent structured information (similar to ‘records’ or ‘structs’ in other languages).

How to Convert a Single List to a Dictionary in Python

Provided that a list is symmetric (containing equal potential key-value pairs), you can convert it to a dictionary using the for loop.

To do this, place your loop in a dictionary comprehension:

m = ["frog", "dog", "Goat", "cat"]
d = {m[a]:m[a + 1] for a in range(0, len(m), 2)}
print(d)
Output: {'frog': 'dog', 'Goat': 'cat'}

The code may look complex at first, but it actually isn't. You're only telling Python to pick a pair each time it iterates through your list. Then it should make every item on the left of each pair the key to the one on its right side, which is its value.

The integer (2) within the range parenthesis, however, ensures that your code only accepts symmetric lists.

To understand its function, change the integer from 2 to 3. Then add an item to the list before running your code.

Related: How to Run a Python Script

To achieve this without using the for loop, you can also use the built-in dict and zip functions of Python:

a = iter(m) # spin up an iterator on the list
result = dict(zip(a, a)) # Convert the iterated items into key-value pairs
print(result)
Output: {'frog': 'dog', 'Goat': 'cat'}

Unlike the looping method that you used earlier, the dict(zip()) function ignores any item without a pair.

For instance, if there are five items in a list, it ignores the fifth one and creates a matching key-value pair with the first four items:

m = ["first", "second", "third", "fourth", "fifth_odd"]
a = iter(m)
result = dict(zip(a, a))
print(result)
Output: {'first': 'second', 'third': 'fourth'}

How to Create Nested Dictionary in Python

June 27, 2021October 10, 2021 0 Comments 3 level nested dictionary python, add elements to nested dictionary python, how to access nested dictionary in python, how to create nested dictionary in python, how to create nested dictionary in python using, nested dictionary python, python create nested dictionary

In this tutorial, we are going to see how to create nested dictionary in Python. A dictionary in Python works in a similar way to a dictionary in the real world. The keys of a dictionary must be unique and have an immutable data type, such as string, integer, etc… but the values can be repeated many times and be of any type.

In Python, a dictionary is an unordered collection. For example:

dictionary = {'key1' : 'value1', 'key2': 'value2'}


What is a nested dictionary in Python?

In Python, a nested dictionary is a dictionary within another dictionary.

nested_dictionary = { 'dict_1': { 'key_1': 'value_1' }, 'dict_2': { 'key_2': 'value_2' } }
Write a Python program to convert a list into a nested dictionary of keys

How to Create Nested Dictionary in Python

In the code below, “students” is a dictionary. Nested dictionaries 1 and 2 are assigned to the “students” dictionary. Here, the two nested dictionaries have the keys “name” and “age” with different values. Next, we display the “students” dictionary.

students = { 1: { 'name': 'Alex', 'age': '15' }, 2: { 'name': 'Bob', 'age': '29' } } print(students)

Output:

{1: {'name': 'Alex', 'age': '15'}, 2: {'name': 'Bob', 'age': '29'}}Access the elements of a nested dictionarystudents = { 1: { 'name': 'Alex', 'age': '15' }, 2: { 'name': 'Bob', 'age': '29' } } print(students[1]['name']) print(students[1]['age'])

Output:

Alex 15

Add an element to a nested dictionarystudents = { 1: { 'name': 'Alex', 'age': '15' }, 2: { 'name': 'Bob', 'age': '29' } } students[3] = {} students[3]['name'] = 'Jean' students[3]['age'] = '22' print(students[3])

Output:

{'name': 'Jean', 'age': '22'}
Write a Python program to convert a list into a nested dictionary of keys
MCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews. Spread the loveRead More
  • Button Tkinter | Python 3
  • Label Tkinter | Python 3
  • Text Tkinter | Python 3
  • Entry Tkinter | Python 3
  • Message Tkinter | Python 3
  • Checkbutton Tkinter | Python 3
  • Radiobutton Tkinter | Python 3
  • Menu Tkinter | Python 3
  • Menubutton Tkinter | Python 3
  • Frame Tkinter | Python 3
  • Scrollbar Tkinter | Python 3
  • Spinbox Tkinter | Python 3
  • Listbox Tkinter | Python 3
  • Canvas Tkinter | Python 3
  • tkMessageBox Tkinter | Python 3
  • LabelFrame Tkinter | Python 3
  • Scale Tkinter | Python 3
  • Toplevel Tkinter | Python 3
  • PanedWindow Tkinter | Python 3
  • pack() Method in Tkinter Python 3
  • grid() Method in Tkinter Python 3
  • place() Method in Tkinter Python 3
  • How to Get Window Size in Tkinter Python
  • How to Set Default Tkinter Entry Value in Python
  • How to Change the Default Icon on a Tkinter Window
  • How to Bind The Enter key to a Function in Tkinter
  • How to Clear Text From a Text Widget on Click in Tkinter
  • How to Set The Width and Height of a Tkinter Entry
  • How to Get the Input From the Tkinter Text Widget
  • How to Make Tkinter Text Widget Read Only
  • How to Increase Font Size in Text Widget in Tkinter
  • How to Get the Tkinter Label Text
  • How To Show/Hide a Label in Tkinter After Pressing a Button
  • How to Delete Tkinter Button After Click
  • How to Change Label Text on Button Click in Tkinter
  • How to Change the Font Size in a Label in Tkinter Python
  • How to Make a Timer in Python Tkinter
  • How To Display a Tkinter Window in Fullscreen
  • How to Stop a Tkinter Window From Resizing
  • How to Open a New Window With a Button in Python Tkinter
  • How to Disable/Enable Tkinter Button in Python
  • How to Close a Tkinter Window With a Button
  • How to Pass Arguments to Tkinter button’s callback Command?
  • How to Bind Multiple Commands to Tkinter Button
  • How to Change Background Color of the Window in Tkinter Python
  • How to Change Background Color of a Tkinter Button in Python
  • How to Change Text of Button When Clicked in Tkinter Python
  • How to change font and size of buttons in Tkinter Python
  • How to Set Tkinter Window Size – Python
  • How To Add Image To Button In Python Tkinter
  • How to run a python script from the command line in Windows 10
  • How to install Python on Windows
  • How to Install Pip for Python on Windows
  • Python Program to Check a Number or String is Palindrome
  • Palindrome Program In Python Using Recursion
  • What is Django used for?
  • Python – Generate a Random Alphanumeric String
  • How to generate a random number in Python
  • Python – Check if Variable is a Number
  • Python Program to Check Armstrong Number
  • Python Program to Check if a Year is a Leap Year
  • Python program to convert decimal to binary
  • Check if a number is odd or even in Python
  • Factorial in Python
  • Factorial of a Number Using Recursion in Python
  • Selection Sort in Python
  • Insertion Sort in Python
  • Bubble Sort in Python
  • How to check if a list is empty in Python
  • How to Count Occurrences of Each Character in String – Python
  • Python – Read a file line-by-line
  • How to get the path of the current directory in Python
  • How to get file creation and modification date in Python
  • How to extract a zip file in Python
  • How to Recursively Remove a Directory in Python
  • How to check if a file or a directory exists in Python
  • How to move a file or directory in Python
  • How to create a directory in Python
  • How to list all the files in a directory in Python
  • How to delete a file or directory in Python
  • How to check if a directory is empty in Python
  • Python – How to copy files from one directory to another
  • How to Create Nested Dictionary in Python
  • How to add keys and values to a dictionary in Python
  • How to copy a dictionary in Python
  • How to get key by value in dictionary in Python
  • Python – Check if String Contains Substring
  • Python – Remove duplicates from a list
  • How to Remove More Than One Element From List in Python
  • Python – Convert a Tuple to a String
  • Python – Convert list of tuples to list of lists
  • Python – Convert a list of tuples into list
  • How to Convert a List into a Tuple in Python
  • How to Convert a String to Float in Python
  • How to Convert a String to an integer in Python
  • How To Convert String To List in Python
  • How to Convert List to String in Python
  • How to Sort a Dictionary by Value in Python
  • How to Sort a Dictionary by Key in Python
  • How to Check if an Item Exists in a List in Python
  • Python – Check if all elements in a List are the same
  • How to merge two lists in Python
  • Python – How to Insert an element at a specific index in List
  • Python Check If a List Contains Elements of Another List
  • Write a Program to Print the Sum of Two Numbers in Python
  • How to convert a list of key-value pairs to dictionary Python
  • Fibonacci Series in Python using Recursion
  • Fibonacci Series in Python using While Loop
  • Python Program to Display Prime Numbers in a Given Range
  • Python MCQ and Answers – Part 1
  • Python MCQ and Answers – Part 2
  • Python MCQ and Answers – Part 3
  • Python MCQ and Answers – Part 4
  • Python MCQ and Answers – Part 5
  • Python MCQ and Answers – Part 6
  • Python MCQ and Answers – Part 7
  • Python MCQ and Answers – Part 8
  • Python MCQ and Answers – Part 9
  • Python MCQ and Answers – Part 10
  • Python MCQ and Answers – Part 11
  • Python MCQ and Answers – Part 12
  • Python MCQ and Answers – Part 13
  • Python MCQ and Answers – Part 14
  • Python MCQ and Answers – Part 15
  • Python MCQ and Answers – Part 16
  • Python MCQ and Answers – Part 17
  • Python MCQ and Answers – Part 18
  • Python MCQ and Answers – Part 19
  • Python MCQ and Answers – Part 20
  • Lists in Python
  • String Functions and Methods in Python
  • Using Variables In Python
  • Output using print() function in Python
  • Python MCQ and Answers – Lists
  • Python MCQ and Answers – Strings
  • Python MCQ and Answers – Data types
  • Python MCQ and Answers – Variables And Operators – Part 2
  • Python MCQ and Answers – Variables And Operators – Part 1
Spread the love

Nested Dictionary in Python

In the Python programming language, we have the concept of dictionaries. The dictionaries are mutable, and we can easily add and delete the items from the dictionary. It is a collection of unordered data items.

  • A dictionary is consists of two parts and the first is the data set and the second one of its corresponding key value.
  • It also does not allow duplicates in it.
  • Here nested dictionary refers to the dictionary inside a dictionary.
  • In simple words, it refers to the dictionary, which consists of a set of multiple dictionaries.
  • It is used to store the data values in key-value pairs.
  • Nesting Dictionary means putting a dictionary inside another dictionary. Nesting is of great use as the kind of information we can model in programs is expanded greatly.
  • A nested dictionary contains an unordered collection of various dictionaries.
  • Compared with a normal dictionary, it also contains the key and its value pairs.
  • We can access the dictionary using its key.
  • A Nested dictionary can be created in Python by placing the comma-separated dictionaries enclosed within braces.
  • Slicing Nested Dictionary is not possible.
  • We can shrink or grow nested dictionaries as needed.

Syntax of Nested dictionary for adding the various dictionaries into a particular one:

Adding elements to a nested Dictionary can be done in multiple ways. One way to add a dictionary in the Nested dictionary is to add values one be one, Nesteddict[dict][key] = 'value'. Another way is to add the whole dictionary in one go, Nesteddict[dict] = { 'key': 'value'}.

Examples of Nested Dictionary

Let us understand with the help of some examples:

Example 1:

Explanation:

In the above example, we created a dictionary containing the integer key values with the corresponding string values. Here we have symbolized with the student's data in the class having roll number with the corresponding name of each student. Further, we will perform the nested operation inside this dictionary.

The Output of the following Program

Printing the dictionary that contains integer keys with their corresponding values {1: 'Rina', 2: 'Gita', 3: 'Sita'}

Example 2:

Explanation:

We have created a dictionary that does not contain any of the keys with the corresponding values. Further, we will perform the nested operation inside this dictionary.

The Output of the following Program

Simple empty dictionary: { }

Example 3:

Explanation:

We have created a nested dictionary, which contains the empty data set, or an empty dictionary that does not contain any data item with their corresponding key values.

The Output of the following Program

Nested dictionary are as follows - {'dict1': {}, 'dict2': {}, 'dict3': {}}

Example 4:

Explanation:

In the above example, we created a dictionary containing the string key values and corresponding integer values. Here we have symbolized with the student's data in the class having Grade with the corresponding roll number of each student. Further, we will perform the nested operation inside this dictionary.

The Output of the following Program

Printing the dictionary that contains string keys with their corresponding integer values {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}

Example 5:

Explanation:

We have created a dictionary containing the data items in the form of pairs. We have created a list of paired items and made them a dictionary.

The Output of the following Program

Dictionary with each item as a pair: {1: 'silk', 2: 'one'}

Example 6:

Explanation:

We have created three separate dictionaries and assigned the elements at the corresponding key values one by one. This dictionary contains the integer key values with the corresponding string values. Still, we have created it separately, and after that, we have added these dictionaries. Thus, we can perform the addition operation in the dictionary. We will also perform the nested operation inside this dictionary.

The Output of the following Program

Dictionary after adding 3 elements: {1: 'Java', 2: 'Tpoint', 3: 1}

Example 7:

Explanation:

We have created a dictionary, which contains the integer key values with the corresponding string values. Here, we have performed the update and the adding operation in the dictionary. We have also made some changes in it and converted it into a nested dictionary.

The Output of the following Program

Dictionary after adding 3 elements: {'Name': 'JavaTpoint', 1: [11, 12, 13], 'Value': (5, 3, 6)} Updated key value: {'Name': 'JavaTpoint', 1: [11, 12, 13], 'Value': (5, 3, 6), 2: 'JavaTpoint'} Adding a Nested Key: {'Name': 'JavaTpoint', 1: [11, 12, 13], 'Value': (5, 3, 6), 2: 'JavaTpoint', 5: {'Nested': {'5': 'Java', '3': 'T'}}}

Example 8:

Explanation:

We have created a nested dictionary that contains the key values with the corresponding values. Here, we have used the concept of mixed keys, in which keys are not the same. We will extend it and make a nested dictionary with the same keys but different values.

The Output of the following Program

Dictionary with the use of Mixed Keys: {'Name': 'JavaTpoint', 1: [11, 12, 13]}

Example 9:

Explanation:

In the above example, we have created a nested dictionary that contains the key values with the corresponding values, here we have used the concept of the same keys, in which keys are the same, but the corresponding data values are different.

The Output of the following Program

Nested dictionary 2- {'Dict1': {'Name': 'Reena', 'age': '22'}, 'Dict2': {'Name': 'Jatin', 'age': '19'}}

Example 10:

Explanation:

We have created a nested dictionary that contains the integer key values with the corresponding string values. Here, we have first printed the nested dictionary and an empty nested dictionary. We have made some changes and placed the nested dictionary inside the empty dictionary. We have also added the two nested dictionaries.

The Output of the following Program

Nested dictionary 3- {'Dict1': {1: 'J', 2: 'T', 3: 'P'}, 'Dict2': {'Name': 'JTP', 1: [1, 2]}} Initial nested dictionary:- {} After adding dictionary Dict1 {'Dict1': {'name': 'Boby', 'age': 21}}

Let us take a fix example and then see some variations in it, so that we can easily understand it easily:

Example 11:

Explanation:

Here we have created a simple nested dictionary; further, we will make some changes.

The Output of the following Program

{1: {'name': 'Shivam', 'age': '22', 'Id': 10023}, 2: {'name': 'Anjali', 'age': '20', 'Id': 10024}}

Example 12:

Explanation:

Here we have created a nested dictionary and use the [ ] syntax to access the elements from the dictionary, here it is used when we supply the name of the dictionary than in this [ ] square brackets position of the element you want to fetch, and after than in additional [ ] square brackets supply the attribute or the key value that you want to fetch for the particular element.

The Output of the following Program

Shivam 22 10023

Example 13:

Explanation:

Here we have created a nested dictionary, and we want to add more elements to that dictionary. It is all done by using [ ] square brackets syntax, firstly we have created an empty set at position 3 in the dictionary, after than one by one we have filled the data into it, here it is used when we supply the name of the dictionary then in this [ ] square brackets position of the element you want to add and after than in additional [ ] square brackets supply the attribute or the key value that you want to assign for the particular element using the equals to sign.

The Output of the following Program

{'name': 'Tina', 'age': '19', 'Id': '10034'}

Example 14:

Explanation:

Here we have created a nested dictionary, and we want to add more elements to that dictionary. It is all done by using [ ] square brackets syntax. At first, we have created an empty set at position 3 in the dictionary, after that one by one we have filled the data into it.

Here, it is used when we supply the name of the dictionary then in this [ ] square brackets position of the element you want to add and after than in additional [ ] square brackets supply the attribute or the key value that you want to assign for the particular element using the equals to sign.

Now for deleting the particular element, let say the id of student 3 from the nested dictionary; we have to use the ' del ' keyword in it; by using it, we can easily delete the particular value that we want.

The Output of the following Program

{'name': 'Tina', 'age': '19', 'Id': '10034'} {'name': 'Tina', 'age': '19'}

Example 15:

Explanation:

Here we have created a nested dictionary, and we want to add more elements to that dictionary. It is all done by using [ ] square brackets syntax. At first, we have created an empty set at position 3 in the dictionary, after that one by one we have filled the data into it, here it is used when we supply the name of the dictionary then in this [ ] square brackets position of the element you want to add and after than in additional [ ] square brackets supply the attribute or the key value that you want to assign for the particular element using the equals to sign.

For deleting the particular dictionary inside the nested dictionary, we have used the ' del ' keyword and deleted the whole dictionary of student 3 from the student nested dictionary.

The Output of the following Program

{'name': 'Tina', 'age': '19', 'Id': '10034'} {1: {'name': 'Shivam', 'age': '22', 'Id': 10053}, 2: {'name': 'Anjali', 'age': '20', 'Id': 10004}}

Next TopicCollections.UserString in Python


← prev next →