🔍 Filtering Dictionaries
Python provides multiple ways to filter dictionaries based on keys, values, or custom criteria. Understanding these methods is essential for data selection and processing.
# Basic dictionary filtering
scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'Diana': 95}
high_scores = {k: v for k, v in scores.items() if v >= 90}
print(f"High scores: {high_scores}")
🎯 Filtering Methods
Python offers several approaches to filter dictionaries.
Basic Examples
# Different ways to filter dictionaries
scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'Diana': 95}
# Filter by value
high_scores = {k: v for k, v in scores.items() if v >= 90}
print(f"High scores: {high_scores}")
# Filter by key
names_with_a = {k: v for k, v in scores.items() if k.startswith('A')}
print(f"Names starting with A: {names_with_a}")
# Filter by key length
short_names = {k: v for k, v in scores.items() if len(k) <= 3}
print(f"Short names: {short_names}")
# Using filter function
def is_high_score(item):
return item[1] >= 90
high_scores_filter = dict(filter(is_high_score, scores.items()))
print(f"Using filter(): {high_scores_filter}")
🔍 Advanced Filtering
Python allows more sophisticated dictionary filtering operations.
# Advanced filtering examples
students = {
'Alice': {'age': 20, 'score': 85, 'grade': 'B'},
'Bob': {'age': 19, 'score': 92, 'grade': 'A'},
'Charlie': {'age': 21, 'score': 78, 'grade': 'C'},
'Diana': {'age': 20, 'score': 95, 'grade': 'A'}
}
# Filter by nested value
a_students = {k: v for k, v in students.items() if v['grade'] == 'A'}
print(f"A students: {a_students}")
# Multiple conditions
young_high_performers = {k: v for k, v in students.items()
if v['age'] < 21 and v['score'] >= 90}
print(f"Young high performers: {young_high_performers}")
# Filter and transform
names_scores = {k: v['score'] for k, v in students.items()
if v['score'] >= 85}
print(f"Names and scores >= 85: {names_scores}")
# Custom filter function
def meets_criteria(student_data):
name, data = student_data
return data['age'] >= 20 and data['score'] >= 85
qualified = dict(filter(meets_criteria, students.items()))
print(f"Qualified students: {qualified}")
🎯 Key Takeaways
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.