Pythonにおける辞書の基礎

Pythonでは辞書型データを{}で定義します。辞書はキーと値のペアを保持するデータ構造です。

character_1 = {'status':'active','score':100}

値の取得方法

current_score = character_1['score']
print(f"獲得ポイント: {current_score}")

辞書の操作(作成・変更・削除)

character_1 = {}
character_1['status'] = 'inactive'
character_1['score'] = 50

print(character_1)

character_1 = {'status':'active'}
print(f"キャラクター状態: {character_1['status']}")

character_1['status'] = 'paused'
print(f"キャラクター状態: {character_1['status']}")
character_1 = {'x':0,'y':25,'movement':'normal'}
print(f"初期X座標: {character_1['x']}")

if character_1['movement'] == 'slow':
    x_step = 1
elif character_1['movement'] == 'normal':
    x_step = 2
else:
    x_step = 3

character_1['x'] += x_step
print(f"更新後X座標: {character_1['x']}")

character_1 = {'status':'active','score':100}
print(character_1)

del character_1['score']
print(character_1)

複数行での定義

user_prefs = {
    'taro':'javascript',
    'hanako':'java',
    'jiro':'typescript',
    'sachiko':'javascript',
}

print(f"{user_prefs['hanako'].title()}が{user_prefs['hanako']}を好む")

辞書のイテレーション

account_1 = {
    'login':'user123',
    'first_name':'john',
    'last_name':'doe',
}

for key, value in account_1.items():
    print(f"\nキー: {key}")
    print(f"値: {value}")

キーと値の名称は任意に設定可能

  1. キーの列挙
user_prefs = {
    'taro':'javascript',
    'hanako':'java',
    'jiro':'typescript',
    'sachiko':'javascript',
}
for name in user_prefs.keys():
    print(name.title())
  1. ソート順でのキー列挙
user_prefs = {
    'taro':'javascript',
    'hanako':'java',
    'jiro':'typescript',
    'sachiko':'javascript',
}

for name in sorted(user_prefs.keys()):
    print(f"{name.title()}、ご協力ありがとうございます")
  1. 値の列挙
user_prefs = {
    'taro':'javascript',
    'hanako':'java',
    'jiro':'typescript',
    'sachiko':'javascript',
}

for lang in user_prefs.values():
    print(f"{lang.title()}が選択されました")
  1. 重複除去(set()使用)
user_prefs = {
    'taro':'javascript',
    'hanako':'java',
    'jiro':'typescript',
    'sachiko':'javascript',
}

for lang in set(user_prefs.values()):
    print(f"{lang.title()}が選択されました")
  1. ネスト構造(リスト内に辞書)
item_1 = {'type':'sword','damage':10}
item_2 = {'type':'shield','defense':5}
item_3 = {'type':'potion','heal':20}

inventory = [item_1,item_2,item_3]

for item in inventory:
    print(item)
inventory = []

for item_id in range(5):
    new_item = {'type':'potion','heal':20,'usage':'single'}
    inventory.append(new_item)

for item in inventory[:2]:
    if item['type'] == 'potion':
        item['type'] = 'elixir'
        item['heal'] = 30
        item['usage'] = 'multiple'

for item in inventory[0:3]:
    print(item)
print('...')
  1. リストを値に格納
user_skills = {
    'taro':['programming','debugging'],
    'hanako':['design','ui'],
    'jiro':['network','security'],
    'sachiko':['database','sql']
}

for name, skills in user_skills.items():
    print(f"\n{name.title()}のスキル:")
    for skill in skills:
        print(f"\t{skill.title()}")
  1. 辞書を値に格納
profiles = {
    'dev1': {
        'first_name':'alice',
        'last_name':'smith',
        'location':'new york',
    },
    'dev2':{
        'first_name':'bob',
        'last_name':'jones',
        'location':'san francisco',
    }
}

for username, details in profiles.items():
    print(f"\nユーザー名: {username}")
    full_name = f"{details['first_name']} {details['last_name']}"
    location = details['location']

    print(f"\tフルネーム: {full_name.title()}")
    print(f"\t所在地: {location.title()}")

タグ: Python 辞書 キー値ペア ループ ネスト

7月17日 22:57 投稿