LoginSignup
0
0

More than 1 year has passed since last update.

ディクショナリ型のメソッドまとめ (Python ver.)

Posted at

このページについて

ディクショナリ型のメソッドをまとめたページです
必要に応じて、順次更新

■ dict.get()

指定したキーに対応する値を取り出す

get_example.py
animals = {'1':'dog','2':'cat','3':'rabbit'}
print(animals['2'])
#cat

■ dict.items()

→キーと値を取り出す

items_example.py
score = {'English':70, 'Math':65, 'Japanese':85}
for key, value in score.items():
    print(key, value)

#English 70
#Math 65
#Japanese 85

■ dict.keys()

→キーの一覧を返す

keys_example.py
score = {'English':70, 'Math':65, 'Japanese':85}
print(score.keys())
#dict_keys(['English', 'Math', 'Japanese'])

for k in score.keys():
    print(k)
# English
# Math
# Japanese

■ dict.pop()

→指定したキーと値を削除する

pop_example.py
fruits = {'apple':15, 'banana':5, 'orange':10}
fruits.pop('banana')
#5
print(fruits)
#{'apple': 15, 'orange': 10}

■ dict.setdefault()

→値を取り出す

setdefault_example.py
fruits = {'apple':15, 'banana':5, 'orange':10}
fruits.setdefault('grape':20)
print(fruits)
#{'apple':15, 'banana':5, 'orange':10, 'grape':20}

■ dict.values()

→辞書の値の一覧を返す

values_exmaple.py
score = {'English':70, 'Math':65, 'Japanese':85}
print(score.values())
#dict_values([70, 65, 85])

for k in score.values():
    print(k)
#70
#65
#85
0
0
0

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
0