Nested Dictionaries

Understanding Python Nested Dictionaries: A Comprehensive Guide









Understanding Python Nested Dictionaries: A Comprehensive Guide | Devyra

Python Nested Dictionaries

A dictionary in Python can contain other dictionaries. This concept is known as nested dictionaries, allowing you to structure complex data hierarchies.

Example 1: Creating Nested Dictionaries

To create a dictionary containing other dictionaries, you can define it as follows:

myfamily = {
  "child1" : {
    "name" : "Emil",
    "year" : 2004
  },
  "child2" : {
    "name" : "Tobias",
    "year" : 2007
  },
  "child3" : {
    "name" : "Linus",
    "year" : 2011
  }
}
  

Example 2: Adding Dictionaries to Another Dictionary

Alternatively, you can create multiple dictionaries and add them to a new one:

child1 = {
  "name" : "Emil",
  "year" : 2004
}
child2 = {
  "name" : "Tobias",
  "year" : 2007
}
child3 = {
  "name" : "Linus",
  "year" : 2011
}

myfamily = {
  "child1" : child1,
  "child2" : child2,
  "child3" : child3
}
  

Accessing Items in Nested Dictionaries

To access data from a nested dictionary, you simply use the keys of the outer and inner dictionaries:

print(myfamily["child2"]["name"])
  

Looping Through Nested Dictionaries

You can loop through a dictionary using the items() method to access both keys and values:

for x, obj in myfamily.items():
  print(x)
  for y in obj:
    print(y + ':', obj[y])
  


More From Author

Copy Dictionaries

How to Copy Dictionaries in Python

Dictionary Methods

Comprehensive Guide to Python Dictionary Methods

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Comments

No comments to show.

Archives

Categories

About Me

Sam Doe

Frequent Traveller

Many lives. Many faces. Different crossroads to different places. 🎶 Listen to my new single release “In My Head” Harlem House Shuffle remix