Practical Techniques and Examples
Now that you have a solid understanding of lists of dictionaries and how to extract values from them, let's explore some practical techniques and examples to help you apply these concepts in your Python programming.
Sorting a List of Dictionaries
Suppose you have a list of dictionaries representing student records, and you want to sort the list based on the students' grades. You can use the sorted()
function and specify the key to sort by.
students = [
{"name": "John", "grade": 85},
{"name": "Jane", "grade": 92},
{"name": "Bob", "grade": 78},
{"name": "Alice", "grade": 90}
]
sorted_students = sorted(students, key=lambda x: x["grade"], reverse=True)
print(sorted_students)
## Output: [{'name': 'Jane', 'grade': 92},
## {'name': 'Alice', 'grade': 90},
## {'name': 'John', 'grade': 85},
## {'name': 'Bob', 'grade': 78}]
Grouping Data by a Key
You can group a list of dictionaries by a specific key and create a dictionary of lists, where the keys are the unique values of the grouping key, and the values are lists of the corresponding dictionaries.
products = [
{"id": 1, "name": "Product A", "category": "Electronics"},
{"id": 2, "name": "Product B", "category": "Electronics"},
{"id": 3, "name": "Product C", "category": "Furniture"},
{"id": 4, "name": "Product D", "category": "Furniture"}
]
grouped_products = {}
for product in products:
category = product["category"]
if category not in grouped_products:
grouped_products[category] = []
grouped_products[category].append(product)
print(grouped_products)
## Output: {'Electronics': [{'id': 1, 'name': 'Product A', 'category': 'Electronics'},
## {'id': 2, 'name': 'Product B', 'category': 'Electronics'}],
## 'Furniture': [{'id': 3, 'name': 'Product C', 'category': 'Furniture'},
## {'id': 4, 'name': 'Product D', 'category': 'Furniture'}]}
You can use list comprehensions and other techniques to transform the data stored in a list of dictionaries. For example, you can create a new list of dictionaries with only the desired keys or calculate derived values.
transactions = [
{"id": 1, "amount": 100.0, "currency": "USD"},
{"id": 2, "amount": 75.0, "currency": "EUR"},
{"id": 3, "amount": 50.0, "currency": "USD"}
]
## Extract only the id and amount keys
simple_transactions = [{
"id": t["id"],
"amount": t["amount"]
} for t in transactions]
print(simple_transactions)
## Output: [{'id': 1, 'amount': 100.0}, {'id': 2, 'amount': 75.0}, {'id': 3, 'amount': 50.0}]
## Calculate the USD equivalent of each transaction
usd_transactions = [{
"id": t["id"],
"amount_usd": t["amount"] if t["currency"] == "USD" else t["amount"] * 1.1
} for t in transactions]
print(usd_transactions)
## Output: [{'id': 1, 'amount_usd': 100.0}, {'id': 2, 'amount_usd': 82.5}, {'id': 3, 'amount_usd': 50.0}]
By exploring these practical techniques and examples, you can enhance your ability to work with lists of dictionaries and apply them effectively in your Python projects.