Create dictionary from nested list Python

Python Nested Dictionary

In this article, you’ll learn about nested dictionary in Python. More specifically, you’ll learn to create nested dictionary, access elements, modify them and so on with the help of examples.

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

dictionary = {'key' : 'value', 'key_2': 'value_2'}

Here, dictionary has a key:value pair enclosed within curly brackets {}.

To learn more about dictionary, please visit Python Dictionary.

Python – Create Nested Dictionary using given List

Given a list and dictionary, map each element of list with each item of dictionary, forming nested dictionary as value.

Input : test_dict = {‘Gfg’ : 4, ‘best’ : 9}, test_list = [8, 2]
Output : {8: {‘Gfg’: 4}, 2: {‘best’: 9}}
Explanation : Index-wise key-value pairing from list [8] to dict {‘Gfg’ : 4} and so on.

Input : test_dict = {‘Gfg’ : 4}, test_list = [8]
Output : {8: {‘Gfg’: 4}}
Explanation : Index-wise key-value pairing from list [8] to dict {‘Gfg’ : 4}.

Method #1 : Using loop + zip[]

This is one of the ways in which this task can be performed. In this, we combine both the lists using zip[] and loop is used to do iteration of zipped keys and dictionary construction.



Python3




# Python3 code to demonstrate working of

# Nested Dictionary with List

# Using loop + zip[]

# initializing dictionary and list

test_dict = {'Gfg' : 4, 'is' : 5, 'best' : 9}

test_list = [8, 3, 2]

# printing original dictionary and list

print["The original dictionary is : " + str[test_dict]]

print["The original list is : " + str[test_list]]

# using zip[] and loop to perform

# combining and assignment respectively.

res = {}

for key, ele in zip[test_list, test_dict.items[]]:

res[key] = dict[[ele]]

# printing result

print["The mapped dictionary : " + str[res]]

Output The original dictionary is : {'Gfg': 4, 'is': 5, 'best': 9} The original list is : [8, 3, 2] The mapped dictionary : {8: {'Gfg': 4}, 3: {'is': 5}, 2: {'best': 9}}

Method #2 : Using dictionary comprehension + zip[]

This is yet another way in which this task can be performed. In this, we perform similar task as above method, but in one liner using dictionary comprehension

Python3




# Python3 code to demonstrate working of

# Nested Dictionary with List

# Using dictionary comprehension + zip[]

# initializing dictionary and list

test_dict = {'Gfg' : 4, 'is' : 5, 'best' : 9}

test_list = [8, 3, 2]

# printing original dictionary and list

print["The original dictionary is : " + str[test_dict]]

print["The original list is : " + str[test_list]]

# zip[] and dictionary comprehension mapped in one liner to solve

res = {idx: {key : test_dict[key]} for idx, key in zip[test_list, test_dict]}

# printing result

print["The mapped dictionary : " + str[res]]

Output The original dictionary is : {'Gfg': 4, 'is': 5, 'best': 9} The original list is : [8, 3, 2] The mapped dictionary : {8: {'Gfg': 4}, 3: {'is': 5}, 2: {'best': 9}}




Article Tags :

Python

Python Programs

Python dictionary-programs

Python list-programs

Read Full Article

Python Nested Dictionary

Prerequisite – Python dictionary
A Dictionary in Python works similar to the Dictionary in the real world. Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers and tuples, but the key-values can be repeated and be of any type.
Nested Dictionary: 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.

Python3




nested_dict = { 'dict1': {'key_A': 'value_A'},

'dict2': {'key_B': 'value_B'}}

Python3




# As shown in image

# Creating a Nested Dictionary

Dict = {1: 'Geeks', 2: 'For', 3: {'A' : 'Welcome', 'B' : 'To', 'C' : 'Geeks'}}

Creating a Nested Dictionary

In Python, a Nested dictionary can be created by placing the comma-separated dictionaries enclosed within braces.



Python3




# Empty nested dictionary

Dict = { 'Dict1': { },

'Dict2': { }}

print["Nested dictionary 1-"]

print[Dict]

# Nested dictionary having same keys

Dict = { 'Dict1': {'name': 'Ali', 'age': '19'},

'Dict2': {'name': 'Bob', 'age': '25'}}

print["\nNested dictionary 2-"]

print[Dict]

# Nested dictionary of mixed dictionary keys

Dict = { 'Dict1': {1: 'G', 2: 'F', 3: 'G'},

'Dict2': {'Name': 'Geeks', 1: [1, 2]} }

print["\nNested dictionary 3-"]

print[Dict]

Output:

Nested dictionary 1- {'Dict1': {}, 'Dict2': {}} Nested dictionary 2- {'Dict1': {'name': 'Ali', 'age': '19'}, 'Dict2': {'name': 'Bob', 'age': '25'}} Nested dictionary 3- {'Dict1': {1: 'G', 2: 'F', 3: 'G'}, 'Dict2': {1: [1, 2], 'Name': 'Geeks'}}

Adding elements to a Nested Dictionary

Addition of 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, Nested_dict[dict][key] = ‘value’. Another way is to add the whole dictionary in one go, Nested_dict[dict] = { ‘key’: ‘value’}.

Python3




Dict = { }

print["Initial nested dictionary:-"]

print[Dict]

Dict['Dict1'] = {}

# Adding elements one at a time

Dict['Dict1']['name'] = 'Bob'

Dict['Dict1']['age'] = 21

print["\nAfter adding dictionary Dict1"]

print[Dict]

# Adding whole dictionary

Dict['Dict2'] = {'name': 'Cara', 'age': 25}

print["\nAfter adding dictionary Dict1"]

print[Dict]

Output:

Initial nested dictionary:- {} After adding dictionary Dict1 {'Dict1': {'age': 21, 'name': 'Bob'}} After adding dictionary Dict1 {'Dict1': {'age': 21, 'name': 'Bob'}, 'Dict2': {'age': 25, 'name': 'Cara'}}

Access elements of a Nested Dictionary

In order to access the value of any key in nested dictionary, use indexing [] syntax.

Python3




# Nested dictionary having same keys

Dict = { 'Dict1': {'name': 'Ali', 'age': '19'},

'Dict2': {'name': 'Bob', 'age': '25'}}

# Prints value corresponding to key 'name' in Dict1

print[Dict['Dict1']['name']]

# Prints value corresponding to key 'age' in Dict2

print[Dict['Dict2']['age']]

Output:

Ali 25

Deleting dictionaries from a Nested Dictionary

Deletion of dictionaries from a nested dictionary can be done either by using del keyword or by using pop[] function.

Python3




Dict = {'Dict1': {'name': 'Ali', 'age': 19},

'Dict2': {'name': 'Bob', 'age': 21}}

print["Initial nested dictionary:-"]

print[Dict]

# Deleting dictionary using del keyword

print["\nDeleting Dict2:-"]

del Dict['Dict2']

print[Dict]

# Deleting dictionary using pop function

print["\nDeleting Dict1:-"]

Dict.pop['Dict1']

print [Dict]

Output:

Initial nested dictionary:- {'Dict2': {'name': 'Bob', 'age': 21}, 'Dict1': {'name': 'Ali', 'age': 19}} Deleting Dict2:- {'Dict1': {'name': 'Ali', 'age': 19}} Deleting Dict1:- {}




Article Tags :

Python

python-dict

Python-nested-dictionary

Practice Tags :

python-dict

Read Full Article

How do I convert a nested list to a dictionary?

Converting a Nested List to a Dictionary Using Dictionary Comprehension. We can convert a nested list to a dictionary by using dictionary comprehension. It will iterate through the list. It will take the item at index 0 as key and index 1 as value.

Can you nest a dictionary in a list?

Slicing Nested Dictionary is not possible. We can shrink or grow nested dictionary as need. Like Dictionary, it also has key and value. Dictionary are accessed using key.

How do I access nested dictionaries?

Access Nested Dictionary Items You can access individual items in a nested dictionary by specifying key in multiple square brackets. If you refer to a key that is not in the nested dictionary, an exception is raised. To avoid such exception, you can use the special dictionary get[] method.

What function could you use to create a complete copy of a nested dictionary?

The copy method which is part of the dict object, only creates a shallow copy. Instead, you should import the copy module [or just the deepcopy function from this module] and use that. print [ “The Shallow Copy changes as well when the original is modified.” ]

How do you access elements in a nested list in Python?

Python Nested List

  1. Create a Nested List. A nested list is created by placing a comma-separated sequence of sublists.
  2. Access Nested List Items by Index.
  3. Negative List Indexing In a Nested List.
  4. Change Nested List Item Value.
  5. Add items to a Nested list.
  6. Remove items from a Nested List.
  7. Find Nested List Length.
  8. Iterate through a Nested List.

5. Data Structures¶

This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.

Video liên quan

Bài mới nhất

Chủ Đề