📊 Sorting Dictionaries

Python provides multiple ways to sort dictionaries by keys or values. Understanding these methods is essential for data organization and presentation.

# Basic dictionary sorting
scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
sorted_by_name = dict(sorted(scores.items()))
print(f"Sorted by name: {sorted_by_name}")

🎯 Sorting Methods

Python offers several approaches to sort dictionaries.

Basic Examples

# Different ways to sort dictionaries
scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78}

# Sort by keys
sorted_by_name = dict(sorted(scores.items()))
print(f"Sorted by name: {sorted_by_name}")

# Sort by values
sorted_by_score = dict(sorted(scores.items(), key=lambda x: x[1]))
print(f"Sorted by score: {sorted_by_score}")

# Sort in reverse order
sorted_reverse = dict(sorted(scores.items(), reverse=True))
print(f"Reverse sorted: {sorted_reverse}")

🔍 Advanced Sorting

Python allows more sophisticated dictionary sorting operations.

# Advanced sorting examples
students = {
    'Alice': {'age': 20, 'score': 85},
    'Bob': {'age': 19, 'score': 92},
    'Charlie': {'age': 21, 'score': 78}
}

# Sort by nested value
sorted_by_age = dict(sorted(students.items(), 
                           key=lambda x: x[1]['age']))
print(f"Sorted by age: {sorted_by_age}")

# Sort by multiple criteria
sorted_by_score_age = dict(sorted(students.items(),
    key=lambda x: (-x[1]['score'], x[1]['age'])))
print(f"Sorted by score (desc) and age (asc): {sorted_by_score_age}")

# Custom sorting function
def get_average_score(student):
    return sum(student[1].values()) / len(student[1])

sorted_by_avg = dict(sorted(students.items(),
                           key=get_average_score))
print(f"Sorted by average: {sorted_by_avg}")

🎯 Key Takeaways

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent