October 13, 2024

Python List of Dictionaries

In Python, a list of dictionaries is a common data structure that allows you to store multiple dictionaries in a list. Each dictionary in the list can contain different key-value pairs, and you can access and manipulate these dictionaries using standard list and dictionary operations.

1. Creating a List of Dictionaries

Here’s how you can create a list of dictionaries:

list_of_dicts = [
    {'name': 'Alice', 'age': 30, 'city': 'New York'},
    {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'},
    {'name': 'Charlie', 'age': 35, 'city': 'Chicago'}
]

print(list_of_dicts)
    

2. Accessing Elements

You can access individual dictionaries in the list using their index, and then access specific values using keys:

# Access the first dictionary
first_dict = list_of_dicts[0]

# Access a value in the first dictionary
name = first_dict['name']
print(name)  # Output: Alice

# Access a value directly
city = list_of_dicts[1]['city']
print(city)  # Output: Los Angeles
    

3. Iterating Through the List

To process each dictionary in the list, you can use a for loop:

for person in list_of_dicts:
    print(f"Name: {person['name']}, Age: {person['age']}, City: {person['city']}")
    

4. Adding a New Dictionary

You can add new dictionaries to the list using the append() method:

new_person = {'name': 'Diana', 'age': 28, 'city': 'San Francisco'}
list_of_dicts.append(new_person)

print(list_of_dicts)
    

5. Modifying Existing Dictionaries

You can modify the values in existing dictionaries by accessing them via their index:

# Modify age of the first person
list_of_dicts[0]['age'] = 31

print(list_of_dicts[0])
    

6. Removing Dictionaries

To remove a dictionary from the list, use the del statement or remove() method:

# Remove the second dictionary
del list_of_dicts[1]

print(list_of_dicts)
    
# Alternatively, use remove() if you know the dictionary
# list_of_dicts.remove({'name': 'Charlie', 'age': 35, 'city': 'Chicago'})
    

7. Filtering Dictionaries

To filter dictionaries based on a condition, use list comprehensions:

# Filter people older than 30
filtered_list = [person for person in list_of_dicts if person['age'] > 30]

print(filtered_list)
    

8. Sorting Dictionaries

You can sort the list of dictionaries based on a specific key using the sorted() function:

# Sort by age
sorted_list = sorted(list_of_dicts, key=lambda x: x['age'])

print(sorted_list)
    

9. Conclusion

A list of dictionaries is a flexible and powerful data structure in Python that allows you to manage collections of dictionaries efficiently. With standard list and dictionary operations, you can create, access, modify, and process data in various ways.