Python でのラムダ関数を使用した辞書値の更新方法

PythonBeginner
オンラインで実践に進む

はじめに

このチュートリアルでは、Python で辞書の値の更新にラムダ関数を使用する方法を探求します。ラムダ関数は、辞書を扱う際にコードをより簡潔で読みやすくすることができる、コンパクトな無名関数です。このガイドの終わりには、これらの強力なツールを使用して、Python プログラムでの辞書操作を効率化する方法を理解できるようになります。

ラムダ関数の使用開始

このステップでは、ラムダ関数とは何か、そして Python でそれらを作成する方法を学びます。

ラムダ関数とは?

ラムダ関数は、lambda キーワードで定義される、小さな無名関数です。def キーワードで宣言される通常の関数とは異なり、ラムダ関数は 1 行で記述でき、名前を必要としません。これらは、すばやく実行する必要がある単純な操作に最適です。

ラムダ関数の基本的な構文は次のとおりです。

lambda arguments: expression

ここで、arguments は関数の入力であり、expression は結果を生成する操作です。

最初のラムダ関数の作成

簡単なラムダ関数を作成し、それがどのように機能するかを見てみましょう。「File」>「New File」をトップメニューバーでクリックして、コードエディターで新しい Python ファイルを開きます。ファイル名を lambda_basics.py とし、/home/labex/project ディレクトリに保存します。

ファイルに次のコードを追加します。

## 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))

ターミナルを開き(まだ開いていない場合)、以下を実行してコードを実行します。

python3 lambda_basics.py

次の出力が表示されるはずです。

Regular function result: 8
Lambda function result: 8

両方の関数は同じ操作を実行しますが、ラムダバージョンの方が簡潔です。

ラムダ関数を使用する状況

ラムダ関数は、次のような状況で最も役立ちます。

  1. 短期間だけ使用する単純な関数が必要な場合
  2. 関数を別の関数の引数として渡したい場合
  3. コレクション内の項目に単純な操作を適用する必要がある場合

別の例を見てみましょう。次のコードを lambda_basics.py ファイルに追加します。

## 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)

ファイルをもう一度実行します。

python3 lambda_basics.py

出力には、次が含まれるようになります。

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

この例では、map および filter 組み込み関数でラムダ関数を使用して、数値のリストを変換およびフィルタリングしました。これらの種類の操作は、次のステップで辞書を操作する際に役立ちます。

Python での辞書の理解

辞書でラムダ関数を使用する前に、Python で辞書がどのように機能するかを理解していることを確認しましょう。

辞書とは?

辞書は、キーと値のペアのコレクションです。各キーは値に接続されており、キーがわかれば値をすばやくアクセスできます。辞書は可変(mutable)であり、辞書が作成された後で項目を変更、追加、または削除できます。

辞書の作成とアクセス

/home/labex/project ディレクトリに dictionary_basics.py という新しいファイルを作成し、次のコードを追加しましょう。

## 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}")

ファイルを実行します。

python3 dictionary_basics.py

次のような出力が表示されるはずです。

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

辞書メソッドの使用

辞書には、いくつかの便利なメソッドがあります。dictionary_basics.py ファイルに次のコードを追加しましょう。

## 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)

ファイルをもう一度実行します。

python3 dictionary_basics.py

追加の出力が表示されるはずです。

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

これで、ラムダ関数と辞書の両方を理解できたので、次のステップでそれらを組み合わせる準備ができました。

ラムダ関数を使用して辞書値を更新する

ラムダ関数と辞書の両方を理解したので、ラムダ関数を使用して辞書値を更新する方法を見てみましょう。

ラムダ関数による基本的な辞書更新

/home/labex/project ディレクトリに update_dictionaries.py という新しいファイルを作成し、次のコードを追加しましょう。

## 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)

ファイルを実行します。

python3 update_dictionaries.py

次のような出力が表示されるはずです。

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}

何が起こったのかを分解してみましょう。

  1. 商品価格の辞書を作成しました。
  2. 10% の割引を適用するために、単純な計算を含む辞書内包表記を使用しました。
  3. map() を使用し、結果を辞書に変換するヘルパー関数 apply_to_dict を作成しました。
  4. この関数をラムダ関数と共に使用して、20% の価格上昇を適用しました。

ラムダ関数による条件付き更新

次に、辞書値を条件付きで更新してみましょう。update_dictionaries.py ファイルに次のコードを追加します。

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)

ファイルをもう一度実行します。

python3 update_dictionaries.py

これで、追加の出力が表示されるはずです。

--- 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}

この例では、次のことを行いました。

  1. 価格に基づいて異なる割引率を適用するために、辞書内包表記で条件式を使用しました。
  2. ラムダ関数を使用して項目をフィルタリングし、別のラムダ関数でフィルタリングされた項目のみを更新する関数を作成しました。
  3. この関数を適用して、文字「a」で始まる商品にのみ 50% の割引を与えました。

これらの例は、ラムダ関数が、特に Python の map()filter() などの組み込み関数と組み合わせた場合に、辞書の更新をより簡潔で読みやすくする方法を示しています。

高度なアプリケーション:辞書のソートと変換

辞書データに焦点を当て、ラムダ関数と辞書のより高度なアプリケーションをいくつか見ていきましょう。

ラムダ関数による辞書のソート

Python の辞書はデフォルトでは順序付けされていませんが、特定の順序で処理する必要がある場合があります。/home/labex/project ディレクトリに advanced_dictionary_ops.py という新しいファイルを作成し、次のコードを追加しましょう。

## 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)

ファイルを実行します。

python3 advanced_dictionary_ops.py

次のような出力が表示されるはずです。

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}

この例では、sorted() 関数をラムダ関数と共に使用して、辞書をさまざまな方法でソートしました。

  • キー(学生名)別
  • 値(スコア)を昇順
  • 値(スコア)を降順

また、スライシング [:3] を使用して、ソート後に上位 3 人の学生のみを取得しました。

辞書値の変換

次に、辞書内の値を変換する方法を見てみましょう。advanced_dictionary_ops.py ファイルに次のコードを追加します。

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)}")

ファイルをもう一度実行します。

python3 advanced_dictionary_ops.py

これで、追加の出力が表示されるはずです。

--- 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

この例では、次のことを行いました。

  1. 辞書内包表記を使用して、摂氏から華氏に温度を変換しました。
  2. ヘルパー関数を使用して、温度を「Cool」、「Moderate」、または「Warm」に分類しました。
  3. reduce() 関数をラムダ関数と共に使用して、都市を温度カテゴリ別にグループ化しました。

これらのテクニックは、ラムダ関数が複雑な辞書操作をより簡潔で読みやすくする方法を示しています。ご覧のとおり、ラムダ関数を Python の組み込み関数と辞書操作と組み合わせることで、データ操作のための強力なツールが提供されます。

まとめ

このチュートリアルでは、Python でラムダ関数を使用して辞書値を更新する方法を学習しました。以下をカバーしました。

  • ラムダ関数とその構文の理解
  • Python での辞書の操作
  • ラムダ関数を使用した辞書値の条件付きおよび無条件での更新
  • 辞書のソートや値の変換などの高度なアプリケーション
  • ラムダ関数と Python の組み込み関数(map()filter()reduce() など)の組み合わせ

これらのテクニックは、Python で辞書を操作する際に、より簡潔で読みやすいコードを書くのに役立ちます。Python の学習を続けるにつれて、ラムダ関数は、特にデータ操作タスクにおいて、プログラミングツールキットの中でますます貴重なツールになるでしょう。

ラムダ関数は強力ですが、単純な操作に最適であることを覚えておいてください。より複雑なロジックの場合は、コードの可読性と保守性を維持するために、通常の名前付き関数を使用することを検討してください。