はじめに
この実験(Lab)では、キーと値のペアとしてデータを格納するための必須のデータ構造である Python の辞書(dictionary)について、実践的な経験を積みます。辞書の作成と検査、要素へのアクセスと変更、アイテムの追加と削除、および辞書ビューオブジェクトの操作方法を学びます。この実験の終わりまでに、一般的な辞書操作を実行できるようになるでしょう。
この実験(Lab)では、キーと値のペアとしてデータを格納するための必須のデータ構造である Python の辞書(dictionary)について、実践的な経験を積みます。辞書の作成と検査、要素へのアクセスと変更、アイテムの追加と削除、および辞書ビューオブジェクトの操作方法を学びます。この実験の終わりまでに、一般的な辞書操作を実行できるようになるでしょう。
このステップでは、辞書の作成方法と検査方法を学びます。辞書はキーと値のペアの集まりであり、各キーは一意である必要があります。辞書は波括弧 {} または dict() コンストラクタを使用して作成されます。Python 3.7 以降、辞書はアイテムが挿入された順序を保持します。
まず、VS Code エディタの左側にあるファイルエクスプローラーから main.py ファイルを開きます。
main.py に次のコードを追加します。このスクリプトは、辞書を作成するさまざまな方法を示しています。
## 波括弧を使用して空の辞書を作成
empty_dict = {}
print(f"Empty dictionary: {empty_dict}")
print(f"Type of empty_dict: {type(empty_dict)}")
## 初期キーと値のペアを持つ辞書を作成
student_info = {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}
print(f"\nStudent info: {student_info}")
## キーワード引数を使用して dict() コンストラクタで辞書を作成
student_info_kw = dict(name='Bob', age=22, major='Physics')
print(f"Student info (from keywords): {student_info_kw}")
## キーと値のタプルのリストから辞書を作成
student_info_tuples = dict([('name', 'Charlie'), ('age', 28), ('major', 'Chemistry')])
print(f"Student info (from tuples): {student_info_tuples}")
コードを追加した後、Ctrl + S を押してファイルを保存します。
次に、VS Code エディタでターミナルを開き (Ctrl + ~)、次のコマンドを実行してスクリプトを実行します。
python main.py
作成したさまざまな辞書を示す、次の出力が表示されるはずです。
Empty dictionary: {}
Type of empty_dict: <class 'dict'>
Student info: {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}
Student info (from keywords): {'name': 'Bob', 'age': 22, 'major': 'Physics'}
Student info (from tuples): {'name': 'Charlie', 'age': 28, 'major': 'Chemistry'}
このステップでは、Python で空の辞書と初期データを持つ辞書を作成するための基本的な方法を学びました。
このステップでは、辞書内の要素へのアクセス方法と変更方法を学びます。値は、角括弧 [] 内でそのキーを参照することにより取得できます。
まず、main.py から以前の内容をすべて消去します。次に、ファイルに次のコードを追加します。このスクリプトは、辞書データへのアクセス方法と変更方法を示しています。
## サンプル辞書の定義
student_info = {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}
print(f"Original dictionary: {student_info}")
## 角括弧を使用して要素にアクセス
student_name = student_info['name']
print(f"\nStudent Name: {student_name}")
## get() メソッドを使用して要素にアクセス
student_age = student_info.get('age')
print(f"Student Age (using get()): {student_age}")
## get() メソッドは、キーが見つからない場合にデフォルト値を提供できる
student_city = student_info.get('city', 'Not Specified')
print(f"Student City (with default): {student_city}")
## 既存のキーの値を変更
print(f"\nOriginal age: {student_info['age']}")
student_info['age'] = 26
print(f"Modified age: {student_info['age']}")
print(f"\nUpdated dictionary: {student_info}")
ファイルを保存 (Ctrl + S) し、ターミナルからスクリプトを実行します。
python main.py
出力は、値の取得方法と、変更後の辞書がどのように見えるかを示しています。
Original dictionary: {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}
Student Name: Alice
Student Age (using get()): 25
Student City (with default): Not Specified
Original age: 25
Modified age: 26
Updated dictionary: {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}
存在しないキーにアクセスするために角括弧 [] を使用すると KeyError が発生しますが、get() は存在しない可能性のあるキーにアクセスするためのより安全な方法を提供することに注意してください。
このステップでは、辞書に新しい要素を追加する方法と、既存の要素を削除する方法について説明します。新しいキーに値を割り当てることで、新しいキーと値のペアを追加できます。
main.py の内容を次のコードに置き換えてください。このスクリプトは、辞書要素の完全なライフサイクル(追加、更新、さまざまな方法での削除)を示しています。
## サンプル辞書の定義
student_info = {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}
print(f"Initial dictionary: {student_info}")
## 新しいキーと値のペアを追加
student_info['city'] = 'New York'
print(f"After adding 'city': {student_info}")
## pop() を使用して要素を削除
## pop() はキーを削除し、その値を返します
removed_major = student_info.pop('major')
print(f"\nRemoved major: {removed_major}")
print(f"After pop('major'): {student_info}")
## popitem() を使用して最後に挿入された要素を削除
## popitem() は (キー, 値) のペアを削除して返します
removed_item = student_info.popitem()
print(f"\nRemoved item: {removed_item}")
print(f"After popitem(): {student_info}")
## 'del' ステートメントを使用して要素を削除
del student_info['age']
print(f"\nAfter del student_info['age']: {student_info}")
## clear() メソッドは辞書からすべての要素を削除します
student_info.clear()
print(f"After clear(): {student_info}")
ファイルを保存 (Ctrl + S) し、スクリプトを実行します。
python main.py
出力には、変更の各段階での辞書の状態が表示されます。
Initial dictionary: {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}
After adding 'city': {'name': 'Alice', 'age': 26, 'major': 'Computer Science', 'city': 'New York'}
Removed major: Computer Science
After pop('major'): {'name': 'Alice', 'age': 26, 'city': 'New York'}
Removed item: ('city', 'New York')
After popitem(): {'name': 'Alice', 'age': 26}
After del student_info['age']: {'name': 'Alice'}
After clear(): {}
このステップでは、新しい要素の追加方法と、pop(), popitem(), del, clear() を使用した要素の削除方法を学びました。
このステップでは、辞書ビューオブジェクトについて探ります。これらは、辞書のキー、値、またはアイテムのビューを提供する動的なオブジェクトです。辞書に加えられた変更は、ビューに即座に反映されます。
main.py の内容を次のコードに置き換えてください。
## サンプル辞書の定義
student_info = {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}
print(f"Original dictionary: {student_info}\n")
## ビューオブジェクトの取得
keys_view = student_info.keys()
values_view = student_info.values()
items_view = student_info.items()
print(f"Keys View: {keys_view}")
print(f"Values View: {values_view}")
print(f"Items View: {items_view}")
## ビューは動的であり、辞書の変更を反映する
print("\n--- Modifying Dictionary ---")
student_info['city'] = 'New York'
print(f"Dictionary after adding 'city': {student_info}")
print(f"Keys View after modification: {keys_view}")
print(f"Values View after modification: {values_view}")
## ビューオブジェクトを反復処理できる
print("\n--- Iterating over Keys View ---")
for key in keys_view:
print(key)
## ビューをリストなどの他のデータ型に変換できる
keys_list = list(keys_view)
print(f"\nKeys view converted to a list: {keys_list}")
ファイルを保存 (Ctrl + S) し、スクリプトを実行します。
python main.py
出力は、ビューオブジェクトの作成、動的な性質、および反復処理を示しています。
Original dictionary: {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}
Keys View: dict_keys(['name', 'age', 'major'])
Values View: dict_values(['Alice', 26, 'Computer Science'])
Items View: dict_items([('name', 'Alice'), ('age', 26), ('major', 'Computer Science')])
--- Modifying Dictionary ---
Dictionary after adding 'city': {'name': 'Alice', 'age': 26, 'major': 'Computer Science', 'city': 'New York'}
Keys View after modification: dict_keys(['name', 'age', 'major', 'city'])
Values View after modification: dict_values(['Alice', 26, 'Computer Science', 'New York'])
--- Iterating over Keys View ---
name
age
major
city
Keys view converted to a list: ['name', 'age', 'major', 'city']
このステップでは、keys(), values(), items() を使用して辞書の内容の動的なビューを取得する方法を示しました。これは多くのプログラミングタスクで役立ちます。
この実験(Lab)では、Python の辞書(dictionary)に関する実践的な経験を積みました。まず、波括弧 {} と dict() コンストラクタを使用して辞書を作成しました。次に、角括弧表記 [] と get() メソッドを使用して辞書要素にアクセスし、変更する方法を学びました。続いて、pop(), popitem(), del ステートメント,clear() を含む様々な方法で新しいキーと値のペアを追加および削除する練習をしました。最後に、動的な辞書ビュー(keys(), values(), items())を探り、それらが辞書内の変更をどのように反映するか、またそれらを反復処理する方法について理解を深めました。