How to Nest a Dictionary in a List?

How to Nest a Dictionary in a List?

Hi, We all know about dictionaries, which are known for their key-value pairs, and lists, recognized for their ordered collection of items, when combined, offer a powerful tool to structure complex data. In this article, we explore How to Nest a Dictionary in a List.

Nesting a dictionary in a list in Python involves defining a dictionary and placing it inside a list. Example: my_dict = {'key': 'value'}. To nest it: my_list = [my_dict]. Nesting helps organize complex data efficiently, enabling structured storage and retrieval in programming applications.

Basic Nesting: A Single Dictionary in a List

To embark on this journey, let’s first understand the core concept of nesting a single dictionary within a list.

# Define a dictionary 

place = {
  "country": "France",
  "visits": 12,
  "cities": ["Paris", "Lille", "Dijon"]
}

# Nest the dictionary inside a list 

travel_log = [place]

Here, place is a dictionary that holds data about an individual. By enclosing place it within square brackets [], we have placed it inside a list named travel_log.

Extending the Nest: Multiple Dictionaries in a List

Let’s stretch the concept further by adding multiple dictionaries into a list. Each dictionary might represent a different entity or set of values.

# Define additional dictionaries 
place1 = {
  "country": "France",
  "visits": 12,
  "cities": ["Paris", "Lille", "Dijon"]
}
place2 =   "country": "France",
  "visits": 12,
  "cities": ["Paris", "Lille", "Dijon"]
},
{
  "country": "Germany",
  "visits": 5,
  "cities": ["Berlin", "Hamburg", "Stuttgart"]
}

# Nest the dictionaries inside a list 
travel_log = [place1,place2]

Now, travel_log contains two dictionaries, each with its own set of data, but residing together in a unified structure.

Dynamic Addition: Appending a Dictionary to an Existing List

For a dynamic application, you might want to add data on the fly. Appending a new dictionary to an existing list is a straightforward operation:

def add_new_country(a,b,c):
    dir={"country": a,"visits": b,"cities": c}
    travel_log.append(dir)
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)
  • In this example, We are creating a dictionary with counties as key and values as cities, number of visits
  • These complete dictionaries will be added as an item to the list
travel_log = [
{
  "country": "Russia",
  "visits": 2,
  "cities": ["Moscow", "Saint Petersburg"]
},]
  • To add an entry to the list, I have created a function called “add_new_country”, which accepts 3 arguments – country, number of visits, cities
  • Initially, Function will create a dictionary and append the item to the list
travel_log.append(dir)

Complete Code:

travel_log = [
{
  "country": "France",
  "visits": 12,
  "cities": ["Paris", "Lille", "Dijon"]
},
{
  "country": "Germany",
  "visits": 5,
  "cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
def add_new_country(a,b,c):
    dir={"country": a,"visits": b,"cities": c}
    travel_log.append(dir)
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)

Navigating through Nested Structures

Data retrieval and manipulation within this nested structure involve utilizing both list indices and dictionary keys.

# Access data: Check number of visit to the contries France

print(travel_log[0]['visits']) 

# Output: 12 Visits 

# Modify data: Update Cathy’s location 

travel_log[0]['country'] = 'France'

Iterative Operations on Nested Structures

Loops can be employed to iterate over the list, accessing and manipulating each enclosed dictionary.

for log in travel_log:
    print(f"country: {log['country']}, visits: {log['visits']}, cities: {log['cities']}")

Output:

country: France, visits: 12, cities: ['Paris', 'Lille', 'Dijon']
country: Germany, visits: 5, cities: ['Berlin', 'Hamburg', 'Stuttgart']
country: Russia, visits: 2, cities: ['Moscow', 'Saint Petersburg']

Conclusion

In conclusion, the nesting of dictionaries in lists allows us to create a multi-dimensional data structure that is capable of storing and managing data in a comprehensive and organized manner. This method can be effectively utilized to address various data management needs in programming, providing a nuanced approach to data storage and retrieval.

Good Luck with your Learning !!

Read More:

How to Make Jarvis With Dialogflow and Python

How do I reinstall Anaconda Python

How do I print an empty line in Python?

Coding Spell Python Journey | About Us 

Latest posts by Muhammad Usman Shafique (see all)