0
1

More than 3 years have passed since last update.

pythonの勉強 update()による辞書の更新

Last updated at Posted at 2019-11-22

update()だよ。2つの辞書を用意して1つの辞書にすることができるよ

members = {'a':1,'b':2,'c':3,'d':4}
others = {'e':5,'f':6}

members.update(others) # 変数membersの後ろに変数othersを更新するよ
print(members)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
others.update(members) # 変数othersの後ろに変数membersを更新するよ
print(others)
{'e': 5, 'f': 6, 'a': 1, 'b': 2, 'c': 3, 'd': 4}

もし、2つの辞書に共通のキーを持っていたら・・・

members = {'a':1,'b':2,'c':3,'d':4}   d=4
others = {'e':5,'d':6}              d=6

members.update(others)
print(members)
{'a': 1, 'b': 2, 'c': 3, 'd': 6, 'e': 5}  d=6に変化
others.update(members)   
print(others)
{'e': 5, 'd': 6, 'a': 1, 'b': 2, 'c': 3} d=6に変化

dの値は上書きされ、キーの数も6つから5つになっている

辞書の中にキーが存在するか確認するよ。

signal = {
    'banana':1,
    'apple':2
}

'banana' in keys() を使って辞書にbananaがあるか確かめるよ。

print('banana' in signal)

結果:True
print(signal.keys()) 変数signalのキーを表示
print(signal.values()) 変数signalの値を表示
list(signal.items()) 変数signalのキー値を表示

dict_keys(['banana', 'apple'])
dict_values([1, 2])
[('banana', 1), ('apple', 2)]
0
1
1

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
1