LoginSignup
0
0

More than 1 year has passed since last update.

【python】勉強メモ-その8 辞書

Last updated at Posted at 2022-12-29

ループを利用した辞書の作成

sample_01.py
# user情報を格納するためのリストを作成
users = []

# 作成したuserのリストに、user情報を辞書型で作成、追加
for user_num in range(10):
    new_user = {"name": "ichiro", "age": 100, "tall": 180}
    persons.append(new_user)

# 5人分だけ出力
for user in users[:5]:
    print(user)

print("")

print(f"作成した人物の人数:{len(users)}")

result.txt
{'name': 'ichiro', 'age': 100, 'tall': 180}
{'name': 'ichiro', 'age': 100, 'tall': 180}
{'name': 'ichiro', 'age': 100, 'tall': 180}
{'name': 'ichiro', 'age': 100, 'tall': 180}
{'name': 'ichiro', 'age': 100, 'tall': 180}

作成したユーザー数:10

値をリスト形式で辞書を作成&値の取得方法

sample_02.py
menu = {
    "Meat_dish": ["焼肉", "すきやき"],
    "fish_dishes": ["刺身", "寿司"]
}

for order in menu["Meat_dish"]:
    print(order)

print("")

for order in menu["fish_dishes"]:
    print(order)

result.txt
焼肉
すきやき

刺身
寿司

辞書の値に辞書を入れる

sample_03.py

users = {
    "yamada" : {
        "first": "ichiro",
        "last": "yamada",
        "age": 20
    },

    "sato": {
        "first": "jiro",
        "last": "sato",
        "age": 10
    }
}

for user_name, user_info in users.items():
    full_name = f'{user_info["last"]} {user_info["first"]}'
    print(full_name)
    print(user_info['age'])
    print("")

result.txt
yamada ichiro
20

sato jiro
10
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0