Python-design-patterns-dictionaries

提供:Dev Guides
移動先:案内検索

Pythonデザインパターン-辞書

辞書は、キーと値の組み合わせを含むデータ構造です。 これらはJSON – JavaScript Object Notationの代わりに広く使用されています。 辞書はAPI(Application Programming Interface)プログラミングに使用されます。 辞書は、オブジェクトのセットを別のオブジェクトのセットにマップします。 辞書は変更可能です。これは、要件に基づいて必要に応じて変更できることを意味します。

Pythonで辞書を実装する方法は?

次のプログラムは、Pythonの作成から実装までの辞書の基本的な実装を示しています。

# Create a new dictionary
d = dict() # or d = {}

# Add a key - value pairs to dictionary
d['xyz'] = 123
d['abc'] = 345

# print the whole dictionary
print(d)

# print only the keys
print(d.keys())

# print only values
print(d.values())

# iterate over dictionary
for i in d :
   print("%s %d" %(i, d[i]))

# another method of iteration
for index, value in enumerate(d):
   print (index, value , d[value])

# check if key exist 23. Python Data Structure –print('xyz' in d)

# delete the key-value pair
del d['xyz']

# check again
print("xyz" in d)

出力

上記のプログラムは、次の出力を生成します-

辞書

注- Pythonでの辞書の実装に関連する欠点があります。

欠点

辞書は、文字列、タプル、リストなどのシーケンスデータ型のシーケンス操作をサポートしていません。 これらは組み込みマッピングタイプに属します。