🎃

Python 辞書型

2021/08/11に公開

Python 辞書型

辞書を定義する

customer={}

辞書にデータをセットする

customer['name'] = 'Ken'
print (name)
Ken
customer['age'] = 40
print(customer)
{'name': 'Ken', 'age': 40}

user = {'id':'a001'}
print(user)
{'id': 'a001'}
print (user ['id'])
a001

product = {'price':'1000'}
product = {'price':1000}
print (product['price'])
1000

product ['price'] + 500
1500 1000に500を足す

辞書からキーを削除する

del customer['age']
print(customer)
{'name': 'Ken'}

辞書にキーが存在するか調べる

'name' in customer  inを使って調べる
True
'age' in customer
False

ifを使う inを入れる

if'name' in customer:
... print(customer['name'])
...
Ken

print(customer['age']) ageは消したのでエラー
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'age'

if,elif を使ってみる

if 'age' in customer:   if ‘age’ そうでなければ’name’
... print(customer['age'])
... elif 'name' in customer:
... print(customer['name'])
...
Ken

Discussion