【Python】Python ~ 基本編 / 辞書 ~

■ はじめに

https://dk521123.hatenablog.com/entry/2019/10/12/084943

の続き。
今回は、ディクショナリ(辞書) (Dictionary)

目次

【1】辞書
【2】基本操作
 1)要素の取得
 2)空かどうかのチェック
 3)キーの存在チェック
 4)ループさせるには
 5)辞書への追加

※ その他の操作は、以下の関連記事を参照のこと。

Python ~ 基本編 / 辞書・あれこれ ~
https://dk521123.hatenablog.com/entry/2020/10/11/000000

 【1】辞書

* { key : value, ... } を使う

構文

dic = {【キー1】: 【バリュー1】, 【キー2】: 【バリュー2】, ...}

サンプル

cities = {"Japan": "Tokyo", "Korea": "Seoul"}

print(len(cities))

 【2】基本操作

1)要素の取得

* 以下の2種類ある

a)["key"] で取得する(e.g. dict["name"])
b)get("key") で取得する(e.g. dict.get("name")) << ★おすすめ★

差異

a)の場合、キーの値がなかったら例外が発生するが
b)の場合、例外は発生せずに、デフォルト値が返ってくる

https://note.nkmk.me/python-dict-get/
サンプル

dict = {"key1":"Hello", "key2":"World"}

# Hello
print(dict.get("key1"))
# World
print(dict.get("key2"))
# None
print(dict.get("key3"))
# !!!
print(dict.get("key3", "!!!"))

2)空かどうかのチェック

* (色々あるが)『not dict』を使う

サンプル

sample_dict = {}
if not sample_dict:
  print('Empty')
else:
  print('Not Empty')

3)キーの存在チェック

* 『"キー" in dict』を使う

サンプル

sample_dict = {'key1': 'value1', 'key2': 'value2'}

# True
print('key1' in sample_dict)

# False
print('keyX' in sample_dict)

4)ループさせるには

* items()を使う

サンプル

for key, value in cities.items():
  print(key + " " + value)

for index, (key, value) in enumerate(cities.items()):
  print(index + " : " + key + " " + value)

[補足1] キーのみでループしたい場合

# keys() を使う
for key in cities.keys():
  print(key)

[補足2] index 付でループしたい場合

demo_dict = {
  "JP": "japan",
  "US": "USA"
}

for (index, elements) in enumerate(demo_dict.items()):
  # 0 ('JP', 'japan')
  print(index, elements)
  # 0 JP japan
  print(index, elements[0], elements[1])

5)辞書への追加

a)update() を使う
b)["KEY"] = "VALUE" を使う << ★こっちのほうがいい★

a)update() を使う

main_dict = {}
main_dict.update({"JP": "Japan"})
main_dict.update({"US": "Unite States"})

for key, value in main_dict.items():
  print(key + " " + value)

b)["KEY"] = "VALUE" を使う

main_dict = {}
# 注意:update() だとリストはつかない(例外がでる)
main_dict["JP"] = ["Japan", "Tokyo"]
main_dict["US"] = ["Unite States", "New York"]

for key, values in main_dict.items():
  for value in values:
    print(key + " " + value)

関連記事

Python ~ 基本編 / 辞書・あれこれ ~
https://dk521123.hatenablog.com/entry/2020/10/11/000000
Python ~ 基本編 / リスト ~
https://dk521123.hatenablog.com/entry/2019/10/12/084943
Python ~ 基本編 / タプル・集合 ~
https://dk521123.hatenablog.com/entry/2019/10/26/000000
Python ~ 基本編 / ラムダ lambda ~
https://dk521123.hatenablog.com/entry/2019/09/23/000000
Python ~ 基本編 / 文字列 ~
https://dk521123.hatenablog.com/entry/2019/10/12/075251
Python ~ 基本編 / astモジュール ~
https://dk521123.hatenablog.com/entry/2021/10/01/000000