How to use lambda functions to update dictionary values in Python

PythonPythonBeginner
Practice Now

Introduction

In this tutorial, we will explore how to use lambda functions to update dictionary values in Python. Lambda functions are compact, anonymous functions that can make your code more concise and readable when working with dictionaries. By the end of this guide, you will understand how to use these powerful tools to streamline dictionary operations in your Python programs.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/lambda_functions("Lambda Functions") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/conditional_statements -.-> lab-398266{{"How to use lambda functions to update dictionary values in Python"}} python/dictionaries -.-> lab-398266{{"How to use lambda functions to update dictionary values in Python"}} python/function_definition -.-> lab-398266{{"How to use lambda functions to update dictionary values in Python"}} python/lambda_functions -.-> lab-398266{{"How to use lambda functions to update dictionary values in Python"}} python/build_in_functions -.-> lab-398266{{"How to use lambda functions to update dictionary values in Python"}} python/data_collections -.-> lab-398266{{"How to use lambda functions to update dictionary values in Python"}} end

Getting Started with Lambda Functions

In this step, we will learn what lambda functions are and how to create them in Python.

What is a Lambda Function?

A lambda function is a small, anonymous function defined with the lambda keyword. Unlike regular functions declared with the def keyword, lambda functions can be written in a single line and do not need a name. They are perfect for simple operations that you need to perform quickly.

The basic syntax of a lambda function is:

lambda arguments: expression

Here, arguments are the inputs to the function, and expression is the operation that produces the result.

Creating Your First Lambda Function

Let's create a simple lambda function and see how it works. Open a new Python file in the code editor by clicking on "File" > "New File" in the top menu bar. Name the file lambda_basics.py and save it in the /home/labex/project directory.

Add the following code to the file:

## Define a regular function
def add_numbers(x, y):
    return x + y

## Same function as a lambda
add_lambda = lambda x, y: x + y

## Test both functions
print("Regular function result:", add_numbers(5, 3))
print("Lambda function result:", add_lambda(5, 3))

Run the code by opening a terminal (if not already open) and executing:

python3 lambda_basics.py

You should see the following output:

Regular function result: 8
Lambda function result: 8

Both functions perform the same operation, but the lambda version is more concise.

When to Use Lambda Functions

Lambda functions are most useful in situations where:

  1. You need a simple function for a short period
  2. You want to pass a function as an argument to another function
  3. You need to apply a simple operation to items in a collection

Let's see another example. Add the following code to your lambda_basics.py file:

## Using lambda with built-in functions
numbers = [1, 2, 3, 4, 5]

## Square each number using lambda
squared = list(map(lambda x: x**2, numbers))

## Filter even numbers using lambda
evens = list(filter(lambda x: x % 2 == 0, numbers))

print("Original numbers:", numbers)
print("Squared numbers:", squared)
print("Even numbers:", evens)

Run the file again:

python3 lambda_basics.py

The output will now include:

Original numbers: [1, 2, 3, 4, 5]
Squared numbers: [1, 4, 9, 16, 25]
Even numbers: [2, 4]

In this example, we used lambda functions with the map and filter built-in functions to transform and filter a list of numbers. These kinds of operations will be useful when we work with dictionaries in the next steps.

Understanding Dictionaries in Python

Before we use lambda functions with dictionaries, let's make sure we understand how dictionaries work in Python.

What is a Dictionary?

A dictionary is a collection of key-value pairs. Each key is connected to a value, allowing you to quickly access values when you know the key. Dictionaries are mutable, which means you can change, add, or remove items after the dictionary is created.

Creating and Accessing Dictionaries

Let's create a new file called dictionary_basics.py in the /home/labex/project directory and add the following code:

## Creating a dictionary
product_prices = {
    'apple': 1.50,
    'banana': 0.75,
    'orange': 1.20,
    'grapes': 2.50
}

## Accessing dictionary values
print("Price of apple:", product_prices['apple'])

## Adding a new item
product_prices['watermelon'] = 3.75
print("Updated dictionary:", product_prices)

## Modifying an existing item
product_prices['banana'] = 0.85
print("After modification:", product_prices)

## Iterating through a dictionary
print("\nAll products and their prices:")
for product, price in product_prices.items():
    print(f"{product}: ${price:.2f}")

Run the file:

python3 dictionary_basics.py

You should see output similar to this:

Price of apple: 1.5
Updated dictionary: {'apple': 1.5, 'banana': 0.85, 'orange': 1.2, 'grapes': 2.5, 'watermelon': 3.75}
After modification: {'apple': 1.5, 'banana': 0.85, 'orange': 1.2, 'grapes': 2.5, 'watermelon': 3.75}

All products and their prices:
apple: $1.50
banana: $0.85
orange: $1.20
grapes: $2.50
watermelon: $3.75

Using Dictionary Methods

Dictionaries have several useful methods. Let's add the following code to our dictionary_basics.py file:

## Dictionary methods
print("\nDictionary Methods:")
print("Keys:", list(product_prices.keys()))
print("Values:", list(product_prices.values()))
print("Items:", list(product_prices.items()))

## Check if a key exists
if 'apple' in product_prices:
    print("Apple is in the dictionary")

## Get a value with a default if key doesn't exist
price = product_prices.get('pineapple', 'Not available')
print("Price of pineapple:", price)

Run the file again:

python3 dictionary_basics.py

You should see the additional output:

Dictionary Methods:
Keys: ['apple', 'banana', 'orange', 'grapes', 'watermelon']
Values: [1.5, 0.85, 1.2, 2.5, 3.75]
Items: [('apple', 1.5), ('banana', 0.85), ('orange', 1.2), ('grapes', 2.5), ('watermelon', 3.75)]
Apple is in the dictionary
Price of pineapple: Not available

Now that we understand both lambda functions and dictionaries, we are ready to combine them in the next step.

Using Lambda Functions to Update Dictionary Values

Now that we understand both lambda functions and dictionaries, let's see how we can use lambda functions to update dictionary values.

Basic Dictionary Updates with Lambda

Let's create a new file called update_dictionaries.py in the /home/labex/project directory and add the following code:

## Create a dictionary of product prices
prices = {
    'apple': 1.50,
    'banana': 0.75,
    'orange': 1.20,
    'grapes': 2.50
}

print("Original prices:", prices)

## Apply a 10% discount to all prices using lambda and dictionary comprehension
discounted_prices = {item: round(price * 0.9, 2) for item, price in prices.items()}
print("Prices after 10% discount:", discounted_prices)

## Another way: using map() and lambda
## First, let's create a function that applies the map
def apply_to_dict(func, dictionary):
    return dict(map(func, dictionary.items()))

## Now apply a 20% increase using the function and lambda
increased_prices = apply_to_dict(lambda item: (item[0], round(item[1] * 1.2, 2)), prices)
print("Prices after 20% increase:", increased_prices)

Run the file:

python3 update_dictionaries.py

You should see output similar to:

Original prices: {'apple': 1.5, 'banana': 0.75, 'orange': 1.2, 'grapes': 2.5}
Prices after 10% discount: {'apple': 1.35, 'banana': 0.68, 'orange': 1.08, 'grapes': 2.25}
Prices after 20% increase: {'apple': 1.8, 'banana': 0.9, 'orange': 1.44, 'grapes': 3.0}

Let's break down what happened:

  1. We created a dictionary of product prices.
  2. We used a dictionary comprehension with a simple calculation to apply a 10% discount.
  3. We created a helper function apply_to_dict that uses map() and converts the result back to a dictionary.
  4. We used this function with a lambda to apply a 20% price increase.

Conditional Updates with Lambda Functions

Now, let's update our dictionary values conditionally. Add the following code to your update_dictionaries.py file:

print("\n--- Conditional Updates ---")

## Apply different discounts: 15% for items over $1.00, 5% for the rest
varied_discount = {
    item: round(price * 0.85, 2) if price > 1.00 else round(price * 0.95, 2)
    for item, price in prices.items()
}
print("Varied discounts:", varied_discount)

## Using filter and lambda to update only certain items
def update_filtered_items(dictionary, filter_func, update_func):
    ## First, filter the items
    filtered = dict(filter(filter_func, dictionary.items()))
    ## Then, update the filtered items
    updated = {key: update_func(value) for key, value in filtered.items()}
    ## Merge with the original dictionary (only updating filtered items)
    result = dictionary.copy()
    result.update(updated)
    return result

## Apply a 50% discount only to fruits starting with 'a'
special_discount = update_filtered_items(
    prices,
    lambda item: item[0].startswith('a'),
    lambda price: round(price * 0.5, 2)
)
print("Special discount on items starting with 'a':", special_discount)

Run the file again:

python3 update_dictionaries.py

You should now see additional output:

--- Conditional Updates ---
Varied discounts: {'apple': 1.28, 'banana': 0.71, 'orange': 1.02, 'grapes': 2.12}
Special discount on items starting with 'a': {'apple': 0.75, 'banana': 0.75, 'orange': 1.2, 'grapes': 2.5}

In this example:

  1. We used a conditional expression in the dictionary comprehension to apply different discount percentages based on the price.
  2. We created a function that filters items using a lambda function, then updates only the filtered items with another lambda function.
  3. We applied this function to give a 50% discount only to products starting with the letter 'a'.

These examples demonstrate how lambda functions can make dictionary updates more concise and readable, especially when combined with Python's built-in functions like map() and filter().

Advanced Applications: Sorting and Transforming Dictionaries

Let's explore some more advanced applications of lambda functions with dictionaries, focusing on sorting and transforming dictionary data.

Sorting Dictionaries with Lambda Functions

Dictionaries in Python are not ordered by default, but sometimes we need to process them in a specific order. Let's create a new file called advanced_dictionary_ops.py in the /home/labex/project directory and add the following code:

## Create a dictionary of student scores
student_scores = {
    'Alice': 92,
    'Bob': 85,
    'Charlie': 78,
    'David': 95,
    'Eva': 88
}

print("Original student scores:", student_scores)

## Sort by student names (keys)
sorted_by_name = dict(sorted(student_scores.items()))
print("\nSorted by name:", sorted_by_name)

## Sort by scores (values) in ascending order
sorted_by_score_asc = dict(sorted(student_scores.items(), key=lambda item: item[1]))
print("\nSorted by score (ascending):", sorted_by_score_asc)

## Sort by scores (values) in descending order
sorted_by_score_desc = dict(sorted(student_scores.items(), key=lambda item: item[1], reverse=True))
print("\nSorted by score (descending):", sorted_by_score_desc)

## Get the top 3 students by score
top_3_students = dict(sorted(student_scores.items(), key=lambda item: item[1], reverse=True)[:3])
print("\nTop 3 students:", top_3_students)

Run the file:

python3 advanced_dictionary_ops.py

You should see output similar to:

Original student scores: {'Alice': 92, 'Bob': 85, 'Charlie': 78, 'David': 95, 'Eva': 88}

Sorted by name: {'Alice': 92, 'Bob': 85, 'Charlie': 78, 'David': 95, 'Eva': 88}

Sorted by score (ascending): {'Charlie': 78, 'Bob': 85, 'Eva': 88, 'Alice': 92, 'David': 95}

Sorted by score (descending): {'David': 95, 'Alice': 92, 'Eva': 88, 'Bob': 85, 'Charlie': 78}

Top 3 students: {'David': 95, 'Alice': 92, 'Eva': 88}

In this example, we used the sorted() function with lambda functions to sort the dictionary in different ways:

  • By key (student name)
  • By value (score) in ascending order
  • By value (score) in descending order

We also used slicing [:3] to get only the top 3 students after sorting.

Transforming Dictionary Values

Now, let's look at how we can transform the values in a dictionary. Add the following code to your advanced_dictionary_ops.py file:

print("\n--- Transforming Dictionary Values ---")

## Create a dictionary of temperatures in Celsius
celsius_temps = {
    'New York': 21,
    'London': 18,
    'Tokyo': 26,
    'Sydney': 22,
    'Moscow': 14
}

print("Temperatures in Celsius:", celsius_temps)

## Convert Celsius to Fahrenheit: F = C * 9/5 + 32
fahrenheit_temps = {city: round(temp * 9/5 + 32, 1) for city, temp in celsius_temps.items()}
print("Temperatures in Fahrenheit:", fahrenheit_temps)

## Categorize temperatures as cool, moderate, or warm
def categorize_temp(temp):
    if temp < 18:
        return "Cool"
    elif temp < 25:
        return "Moderate"
    else:
        return "Warm"

categorized_temps = {city: categorize_temp(temp) for city, temp in celsius_temps.items()}
print("Categorized temperatures:", categorized_temps)

## Group cities by temperature category using a lambda and reduce
from collections import defaultdict
from functools import reduce

grouped_cities = reduce(
    lambda result, item: result[categorize_temp(item[1])].append(item[0]) or result,
    celsius_temps.items(),
    defaultdict(list)
)

print("\nCities grouped by temperature category:")
for category, cities in grouped_cities.items():
    print(f"{category}: {', '.join(cities)}")

Run the file again:

python3 advanced_dictionary_ops.py

You should now see additional output:

--- Transforming Dictionary Values ---
Temperatures in Celsius: {'New York': 21, 'London': 18, 'Tokyo': 26, 'Sydney': 22, 'Moscow': 14}
Temperatures in Fahrenheit: {'New York': 69.8, 'London': 64.4, 'Tokyo': 78.8, 'Sydney': 71.6, 'Moscow': 57.2}
Categorized temperatures: {'New York': 'Moderate', 'London': 'Moderate', 'Tokyo': 'Warm', 'Sydney': 'Moderate', 'Moscow': 'Cool'}

Cities grouped by temperature category:
Cool: Moscow
Moderate: New York, London, Sydney
Warm: Tokyo

In this example:

  1. We converted temperatures from Celsius to Fahrenheit using a dictionary comprehension.
  2. We categorized temperatures as "Cool", "Moderate", or "Warm" using a helper function.
  3. We used the reduce() function with a lambda to group cities by temperature category.

These techniques demonstrate how lambda functions can make complex dictionary operations more concise and readable. As you can see, combining lambda functions with Python's built-in functions and dictionary operations provides powerful tools for data manipulation.

Summary

In this tutorial, you have learned how to use lambda functions to update dictionary values in Python. We covered:

  • Understanding lambda functions and their syntax
  • Working with dictionaries in Python
  • Using lambda functions to update dictionary values conditionally and unconditionally
  • Advanced applications such as sorting dictionaries and transforming values
  • Combining lambda functions with Python's built-in functions like map(), filter(), and reduce()

These techniques will help you write more concise and readable code when working with dictionaries in Python. As you continue your Python journey, you will find that lambda functions become an increasingly valuable tool in your programming toolkit, especially for data manipulation tasks.

Remember that while lambda functions are powerful, they work best for simple operations. For more complex logic, consider using regular named functions to maintain code readability and maintainability.