Python

How to Create and Use a List of Dictionaries in Python

In Python programming, utilizing the power of lists and dictionaries reveals a versatile outlook for data organization. Specifically, creating a list of dictionaries provides a solid mechanism to summarize the heterogeneous data within a single, coordinated structure. This guide navigates the fundamentals of creating and utilizing such a structure. Looking into Python’s syntax, we will explore the effortless integration of dictionaries within lists, facilitating the storage and retrieval of diverse information. As we unwind the complexities, this will be helpful for both novice and seasoned developers with the proficiency to utilize Python’s capabilities in handling a structured data.

Understanding the Basics

Let’s begin with the basics. A dictionary in Python is a collection of key-value pairs, and a list is an ordered collection of elements. Combining these concepts allows us to create a list of dictionaries where each dictionary represents an item in the list and the keys within each dictionary define specific attributes of that item.

Creating a List of Dictionaries

Creating and utilizing a list of dictionaries in Python is a fundamental skill that enables the developers to manage and manipulate the structured data efficiently. This example examines the complexities of constructing and utilizing these powerful constructs.

students = [
    {"name": "Alice", "age": 25, "grade": "A"},
    {"name": "Bob", "age": 22, "grade": "B"},
    {"name": "Charlie", "age": 24, "grade": "C"}
]

In this example, we have a list named “students” where each element is a dictionary contains information about a student including their name, age, and grade.

Once we have our list of dictionaries, we often need to retrieve a specific information from it to access the data in a list of dictionaries. Accessing the data involves specifying the index of the desired dictionary in the list and then using the respective key. Here, we access the first dictionary in the “students” list and print out its name, age, and grade.

first_student = students[0]
print("Name:", first_student["name"])
print("Age:", first_student["age"])
print("Grade:", first_student["grade"])

A common scenario is needed to iterate through the entire list to perform the operations on each dictionary. This is achieved using loops like the “for” loop in Python. In this example, we iterate through the “students” list, printing the details of each student and separating them with a line.

students = [
    {"name": "Alice", "age": 25, "grade": "A"},
    {"name": "Bob", "age": 22, "grade": "B"},
    {"name": "Charlie", "age": 24, "grade": "C"}
]

for student in students:
    print("Name:", student["name"])
    print("Age:", student["age"])
    print("Grade:", student["grade"])
    print("---")

To modify the data in a list of changeable dictionaries, we can modify their contents. Let’s explore how to update the information for a specific student.

students = [
    {"name": "Alice", "age": 25, "grade": "A"},
    {"name": "Bob", "age": 22, "grade": "B"},
    {"name": "Charlie", "age": 24, "grade": "C"}
]

students[1]["grade"] = "A"
students[2]["age"] = 23

# Print the updated list
for student in students:
    print("Name:", student["name"])
    print("Age:", student["age"])
    print("Grade:", student["grade"])
    print("---")

Here, we change the grade of the second student to “A” and update the age of the third student to 23. To add and remove the dictionaries and dynamically modify the size of our list of dictionaries are common requirements. Adding a new student involves adding a new dictionary to the list.

students = [
    {"name": "Alice", "age": 25, "grade": "A"},
    {"name": "Bob", "age": 22, "grade": "B"},
    {"name": "Charlie", "age": 24, "grade": "C"}
]

# Adding a new student to the list
new_student = {"name": "David", "age": 21, "grade": "B"}
students.append(new_student)

# Print the updated list
for student in students:
    print("Name:", student["name"])
    print("Age:", student["age"])
    print("Grade:", student["grade"])
    print("---")

Here, we attach/add a dictionary that represents a new student named “David” to the “students” list. Opposite to that, removing a student from the list can be achieved using the “remove” method or list comprehension. In this example, we remove the dictionary that represents “Bob” from the “students” list.

students = [
    {"name": "Alice", "age": 25, "grade": "A"},
    {"name": "Bob", "age": 22, "grade": "A"},
    {"name": "Charlie", "age": 24, "grade": "C"}
]

#  Removing a student from the list
students.remove({"name": "Bob", "age": 22, "grade": "A"})

# Print the updated list
for student in students:
    print("Name:", student["name"])
    print("Age:", student["age"])
    print("Grade:", student["grade"])
    print("---")

Sorting a list of dictionaries is a powerful operation which is often required for a better data presentation. Python provides the “sorted” function which allows us to sort the list based on a specific key. Here, we sort the “students” list based on the “age” key, producing a new list named “students_sorted_by_age”.

students = [
    {"name": "Alice", "age": 25, "grade": "A"},
    {"name": "Bob", "age": 22, "grade": "A"},
    {"name": "Charlie", "age": 24, "grade": "C"}
]

#  Sorting a list of dictionaries by age
students_sorted_by_age = sorted(students, key=lambda x: x["age"])

# Print the sorted list
for student in students_sorted_by_age:
    print("Name:", student["name"])
    print("Age:", student["age"])
    print("Grade:", student["grade"])
    print("---")

Filtering the data is essential when we want to extract specific elements from our list of dictionaries that meet a certain criteria. This can be achieved using the list understanding.

students = [
    {"name": "Alice", "age": 25, "grade": "A"},
    {"name": "Bob", "age": 22, "grade": "A"},
    {"name": "Charlie", "age": 24, "grade": "C"}
]

#  Filtering students with age greater than 22
mature_students = [student for student in students if student["age"] > 22]

# Print the filtered list
for student in mature_students:
    print("Name:", student["name"])
    print("Age:", student["age"])
    print("Grade:", student["grade"])
    print("---")

In the next example, we create a new list, “mature_students”, which contains only the students over 22.

Nested dictionaries within a list add a layer of complexity to data organization which allows for the representation of structured and hierarchical information. Let’s look deeper into the concept of nested dictionaries within a list with a more detailed explanation.

#  Using nested dictionaries in a list
students_with_subjects = [
    {"name": "Alice", "subjects": {"Math": "A", "English": "B"}},
    {"name": "Bob", "subjects": {"Math": "B", "English": "A"}},
    {"name": "Charlie", "subjects": {"Math": "C", "English": "B"}}
]

# Accessing subject grades for Bob
print("Math Grade for Bob:", students_with_subjects[1]["subjects"]["Math"])
print("English Grade for Bob:", students_with_subjects[1]["subjects"]["English"])

To understand the nested dictionaries in a list, consider a scenario where each item represents a person. Within each person’s data, there is a need to store the information about their contact details including phone numbers and addresses. This is where the nested dictionaries become essential.

# Example: Nested dictionaries within a list for storing contact information
people_with_contacts = [
    {
        "name": "Alice",
        "contact_info": {
            "phone": "123-456-7890",
            "address": {
                "street": "123 Main St",
                "city": "Anytown",
                "zipcode": "98765"
            }
        }
    },
    {
        "name": "Bob",
        "contact_info": {
            "phone": "987-654-3210",
            "address": {
                "street": "456 Oak Ave",
                "city": "Another Town",
                "zipcode": "54321"
            }
        }
    }
]

In this example, the “people_with_contacts” list contains dictionaries, each representing a person. Each person’s dictionary has two main keys: “name” and “contact_info”. The “contact_info” key, in turn, contains another dictionary with keys for “phone” and “address”.

Accessing the data in nested dictionaries involves combining multiple keys. For instance, let’s retrieve Alice’s phone number:

alice_phone = people_with_contacts[0]["contact_info"]["phone"]
print("Alice's Phone Number:", alice_phone)

Here, we access the first person’s dictionary in the list. Then, we navigate to the “contact_info” dictionary within it and retrieve the “phone” key. The data within the nested dictionaries follows a similar approach to modify the data in nested dictionaries. Let’s update Bob’s address:

people_with_contacts[1]["contact_info"]["address"]["street"] = "789 Pine Blvd"

This code line modifies Bob’s street address within the nested dictionaries.

The nested structure becomes clearer in the loop when going through a list of nested dictionaries. For instance, we print each person’s name and address:

# Example: Nested dictionaries within a list for storing contact information
people_with_contacts = [
    {
        "name": "Alice",
        "contact_info": {
            "phone": "123-456-7890",
            "address": {
                "street": "123 Main St",
                "city": "Anytown",
                "zipcode": "98765"
            }
        }
    },
    {
        "name": "Bob",
        "contact_info": {
            "phone": "987-654-3210",
            "address": {
                "street": "456 Oak Ave",
                "city": "Another Town",
                "zipcode": "54321"
            }
        }
    }
]
people_with_contacts[1]["contact_info"]["address"]["street"] = "789 Pine Blvd"

for person in people_with_contacts:
    print("Name:", person["name"])
    print("Street Address:", person["contact_info"]["address"]["street"])
    print("City:", person["contact_info"]["address"]["city"])
    print("Zipcode:", person["contact_info"]["address"]["zipcode"])
    print("---")

This loop navigates through the list, accessing and printing the details from the nested dictionaries.

Application Cases for Nested Dictionaries

Nested dictionaries in a list are handy when dealing with complex data structures. Consider scenarios like representing a collection of products with detailed specifications, organizing a hierarchy of tasks with subtasks, or managing hierarchical data like organizational charts. Each product in the collection has specifications that are stored within a nested dictionary under the “specs” key.

# Nested dictionaries within a list for storing contact information
people_with_contacts = [
    {
        "name": "Alice",
        "contact_info": {
            "phone": "123-456-7890",
            "address": {
                "street": "123 Main St",
                "city": "Anytown",
                "zipcode": "98765"
            }
        }
    },
    {
        "name": "Bob",
        "contact_info": {
            "phone": "987-654-3210",
            "address": {
                "street": "456 Oak Ave",
                "city": "Another Town",
                "zipcode": "54321"
            }
        }
    }
]
people_with_contacts[1]["contact_info"]["address"]["street"] = "789 Pine Blvd"

for person in people_with_contacts:
    print("Name:", person["name"])
    print("Street Address:", person["contact_info"]["address"]["street"])
    print("City:", person["contact_info"]["address"]["city"])
    print("Zipcode:", person["contact_info"]["address"]["zipcode"])
    print("---")
# Example: Nested dictionaries representing a catalog of products
product_catalog = [
    {"product_id": 1, "name": "Laptop", "specs": {"RAM": "8GB", "Storage": "256GB SSD"}},
    {"product_id": 2, "name": "Smartphone", "specs": {"RAM": "6GB", "Storage": "128GB"}},
    # ... more products
]
# Example: Nested dictionaries representing a catalog of products
product_catalog = [
    {"product_id": 1, "name": "Laptop", "specs": {"RAM": "8GB", "Storage": "256GB SSD"}},
    {"product_id": 2, "name": "Smartphone", "specs": {"RAM": "6GB", "Storage": "128GB"}},
    {"product_id": 3, "name": "Tablet", "specs": {"RAM": "4GB", "Storage": "64GB"}},
    # ... more products
]

# Outputting information about each product and its specifications
for product in product_catalog:
    print(f"Product ID: {product['product_id']}")
    print(f"Name: {product['name']}")
    print("Specifications:")
    print(f"  - RAM: {product['specs']['RAM']}")
    print(f"  - Storage: {product['specs']['Storage']}")
    print("---")

Including nested dictionaries within a list enhances the flexibility and expressiveness of data structures in Python. This approach proves important when dealing with layered or hierarchical information, providing a clear and organized way to represent the complex relationships. As we encounter scenarios that require a complex data representation, the skillful use of nested dictionaries within lists allows us to design an efficient and readable code.

Conclusion

Mastering the creation and utilization of lists of dictionaries in Python is essential for effective data manipulation and organization. From accessing and modifying the data to sorting and filtering, the utility of these constructs enables the developers to handle the diverse scenarios. As we further explore our Python journey, combining these techniques will enhance our ability to work with structured data powerfully and expressively.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.