python辞書操作の概要


pythonの辞書はキー-値ペアに等しく、1つのkeyは1つのvalueに対応します.次に、辞書の一般的な操作1、辞書の作成2、辞書の追加、変更3、辞書or辞書の値の削除4、辞書5の遍歴、ネストをまとめます.
一、辞書の作成
Pythonには2つの方法で辞書を作成することができます.1つ目はカッコを使用することで、もう1つは内蔵関数dict例を使用することです.
>>> info = {'color':'green', 'points':'5'}
>>> info1 = dict(color='green', points='5')
>>> print(info)
>>> print(info1)
{'color': 'green', 'points': '5'}
{'color': 'green', 'points': '5'}

二、辞書の追加or修正
いずれもdict[key]=valueで操作する
#    
>>> info = {'color': 'green', 'points': '5'}
>>> info['color'] = 'blue'
>>> print(info)

{'color': 'blue', 'points': '5'}
#    
>>> info1 = {'color': 'green', 'points': '5'}
>>> info1['position'] = 50
>>> print(info1)

{'color': 'green', 'points': '5', 'position': 50}


三、辞書or辞書の値を削除する
1、辞書del dict 2の削除、辞書の値del dict[key]例の削除
>>> info = {'color': 'green', 'points': '5'}
>>> info1 = {'color': 'green', 'points': '5'}
>>> del info
>>> del info1['color']
>>> print(info)
>>> print(info1)
NameError: name 'info' is not defined
{'points': '5'}

四、辞書を遍歴する
1、dict.items()で遍歴し、辞書のkeyとvalueをそれぞれ取得する
>>> info = {'color': 'green', 'points': '5'}
>>> for key,value in info.items():
>>>     print(key)
>>>     print(value)
color
green
points
5


2、dict.keys()によって、辞書の中のすべてのキー3を遍歴し、dict.values()によって、辞書の中のすべての値を遍歴する
五、辞書の入れ子
1、辞書をリストにネストする
>>> alien1 = {'color':'green','point':5}
>>> alien2 = {'color':'yellow','point':10}
>>> alien3 = {'color':'black','point':15}
>>> aliens = [alien1, alien2, alien3]
>>> for alien in aliens:
>>>     print(alien)
{'color': 'green', 'point': 5}
{'color': 'yellow', 'point': 10}
{'color': 'black', 'point': 15}

2、リストを辞書に埋め込む
3、辞書を辞書に埋め込む