Of course! Let's break down how to use lambda functions with dictionaries in Python.

What is a lambda Function?
A lambda function is a small, anonymous function defined using the lambda keyword. It's a shorthand way to create a simple function without needing the def keyword and a formal function definition.
Syntax:
lambda arguments: expression
Key characteristics:
- Anonymous: It doesn't have a name.
- Single Expression: It can only contain a single expression, which is evaluated and returned.
- Concise: It's used for short, simple operations.
Example: A regular function:

def square(x):
return x * x
The equivalent lambda function:
lambda x: x * x
You can assign it to a variable to use it:
square_lambda = lambda x: x * x print(square_lambda(5)) # Output: 25
Using lambda with Dictionaries
lambda functions are most powerful when used as arguments for other functions, especially those that work on iterables like dictionaries. The most common use cases are map(), filter(), and sorted().
Let's use this sample dictionary for our examples:

people = [
{'name': 'Alice', 'age': 30, 'city': 'New York'},
{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'},
{'name': 'Charlie', 'age': 35, 'city': 'New York'}
]
A. Sorting Dictionaries with sorted()
This is the most frequent use case. You can use a lambda function as the key argument to specify what part of the dictionary should be used for sorting.
Sorting a list of dictionaries by a specific key:
To sort the list of people by their age:
# Sort by 'age'
sorted_by_age = sorted(people, key=lambda person: person['age'])
print(sorted_by_age)
# Output:
# [{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'},
# {'name': 'Alice', 'age': 30, 'city': 'New York'},
# {'name': 'Charlie', 'age': 35, 'city': 'New York'}]
How it works:
sorted(people, ...): Thesorted()function iterates through thepeoplelist.key=...: For each dictionary (which we callpersonin the lambda), it applies thelambdafunction.lambda person: person['age']: This lambda takes one argument (person, which is a dictionary like{'name': 'Alice', ...}) and returns the value associated with the key'age'(e.g.,30).sorted()then uses these returned values (25,30,35) as the sorting keys.
Sorting by multiple keys:
To sort first by city and then by age within the same city:
# Sort by 'city' (ascending) and then by 'age' (ascending)
sorted_by_city_then_age = sorted(
people,
key=lambda person: (person['city'], person['age'])
)
print(sorted_by_city_then_age)
# Output:
# [{'name': 'Alice', 'age': 30, 'city': 'New York'},
# {'name': 'Charlie', 'age': 35, 'city': 'New York'},
# {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}]
The lambda returns a tuple ('city', 'age'), and sorted() uses tuple comparison, which works perfectly for this.
Sorting in descending order:
To sort by age from oldest to youngest, use the reverse=True argument:
# Sort by 'age' in descending order
sorted_by_age_desc = sorted(people, key=lambda person: person['age'], reverse=True)
print(sorted_by_age_desc)
# Output:
# [{'name': 'Charlie', 'age': 35, 'city': 'New York'},
# {'name': 'Alice', 'age': 30, 'city': 'New York'},
# {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}]
B. Transforming Dictionaries with map()
The map() function applies a given function to every item of an iterable (like a list of dictionaries). It returns a map object, which you can convert to a list.
Extracting a specific value from each dictionary:
Let's get a list of all the names:
# Get a list of names names = list(map(lambda person: person['name'], people)) print(names) # Output: ['Alice', 'Bob', 'Charlie']
How it works:
map(...)iterates throughpeople.- For each
person, thelambdaextracts the value for the'name'key. list(...)converts the resulting map object into a list.
Creating a new list of dictionaries with modified values:
Let's create a new list where each dictionary has a new key 'status' based on age:
# Add a 'status' key based on age
people_with_status = list(map(
lambda person: {**person, 'status': 'Adult' if person['age'] >= 30 else 'Young'},
people
))
print(people_with_status)
# Output:
# [
# {'name': 'Alice', 'age': 30, 'city': 'New York', 'status': 'Adult'},
# {'name': 'Bob', 'age': 25, 'city': 'Los Angeles', 'status': 'Young'},
# {'name': 'Charlie', 'age': 35, 'city': 'New York', 'status': 'Adult'}
# ]
How it works:
{**person, 'status': ...}is the dictionary unpacking operator. It creates a new dictionary by copying all key-value pairs from the originalpersondictionary and then adding (or overwriting) the'status'key with the new value.
C. Filtering Dictionaries with filter()
The filter() function constructs an iterator from elements of an iterable for which a function returns True.
Filtering a list of dictionaries based on a condition:
Let's get only the people who live in 'New York':
# Filter people who live in New York
new_yorkers = list(filter(lambda person: person['city'] == 'New York', people))
print(new_yorkers)
# Output:
# [
# {'name': 'Alice', 'age': 30, 'city': 'New York'},
# {'name': 'Charlie', 'age': 35, 'city': 'New York'}
# ]
How it works:
filter(...)iterates throughpeople.- The
lambdachecks if the value of the'city'key is'New York'. It returnsTrueorFalse. filter()keeps only the dictionaries for which the lambda returnedTrue.
Creating a Dictionary with a lambda
Sometimes you might see a lambda used to define a dictionary's values based on some other data, often using dict comprehension (which is often more readable than a map for this task).
Example: Create a dictionary mapping names to ages.
Using dict comprehension (recommended):
name_to_age = {person['name']: person['age'] for person in people}
print(name_to_age)
# Output: {'Alice': 30, 'Bob': 25, 'Charlie': 35}
Using map (less common for this specific task):
# This is less readable and less common for creating dicts
name_to_age_map = dict(map(lambda person: (person['name'], person['age']), people))
print(name_to_age_map)
# Output: {'Alice': 30, 'Bob': 25, 'Charlie': 35}
Summary Table
| Goal | Method | Example |
|---|---|---|
| Sort a list of dicts by a key | sorted() with a lambda key |
sorted(people, key=lambda p: p['age']) |
| Filter a list of dicts by a condition | filter() with a lambda |
list(filter(lambda p: p['city'] == 'NY', people)) |
| Transform values in a list of dicts | map() with a lambda |
list(map(lambda p: {**p, 'status': 'active'}, people)) |
| Create a new dict from an existing one | dict comprehension (preferred) or map() |
{p['name']: p['age'] for p in people} or dict(map(lambda p: (p['name'], p['age']), people)) |
Best Practices and When to Use lambda
- Use
lambdafor simple, one-off operations. If your logic is more than one line or you plan to reuse the function, define it withdeffor better readability and debugging. - Readability is key. If a
lambdabecomes too complex (e.g., nested ternary operators), it's often better to use a standarddeffunction. dictcomprehensions are often better for creating new dictionaries from existing ones than usingmapwith alambda.
