0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

~ 辞書 ~ チートシート

Last updated at Posted at 2024-04-25

#目次
要素の削除 .pop() del dict[]
リストに抽出 list(dict.keys()) list(dict.values())) list(dict.items()))

要素の追加 .setdefault() dict[]
要素の参照 .get() dict[]

#はじめに

チートシートの扱いついてはここを読んでください

#要素の削除

dict.py
dict = {"Oto" : 9, "Ura" : 9, "Niji" : 12, "Yui" : 11, "Hasu" : 9}
print(dict.pop("Oto"))
print(dict)
mat
>>> 9
>>> {"Ura" : 9, "Niji" : 12, "Yui" : 11, "Hasu" : 9}

.pop()で指定したキーの要素を渡し、削除も可能

dict.py
dict = {"Oto" : 9, "Ura" : 9, "Niji" : 12, "Yui" : 11, "Hasu" : 9}
del dict["Oto"]
print(dict)
mat
>>> {"Ura" : 9, "Niji" : 12, "Yui" : 11, "Hasu" : 9}

delで指定したキーの要素を削除できる

#リストに抽出

dict.py
dict = {"Oto" : 9, "Ura" : 9, "Niji" : 12, "Yui" : 11, "Hasu" : 9}
print(list(dict.keys()))
mat
>>> ['Oto', 'Ura', 'Niji', 'Yui', 'Hasu']

list(dict.keys())でキーのみを抽出し配列にできる

dict.py
dict = {"Oto" : 9, "Ura" : 9, "Niji" : 12, "Yui" : 11, "Hasu" : 9}
print(list(dict.values()))
mat
>>> [9, 9, 12, 11, 9]

list(dict.values())で要素のみを抽出し配列にできる

dict.py
dict = {"Oto" : 9, "Ura" : 9, "Niji" : 12, "Yui" : 11, "Hasu" : 9}
print(list(dict.items()))
mat
>>> [('Oto', 9), ('Ura', 9), ('Niji', 12), ('Yui', 11), ('Hasu', 9)]

list(dict.items())でキーと要素の両方を抽出し配列にできる
キーと要素の組はリストではなくタプルであることに注意

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?