1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python_dicのkey検索方法

Last updated at Posted at 2022-03-13

わかりやすい英語記事があったため、ストック。

word_freq = {
"Hello": 56,
"at": 23,
"test": 43,
"this": 78
}
key = 'test'

①keyの有無をif文で判断
if key in word_freq:
print(f"Yes, key: '{key}' exists in dictionary")
else:
print(f"No, key: '{key}' does not exists in dictionary")

②getを使用する
if word_freq.get(key) is not None:
print(f"Yes, key: '{key}' exists in dictionary")
else:
print(f"No, key: '{key}' does not exists in dictionary")

③keyメソッドを使用する
if key in word_freq.keys():
print(f"Yes, key: '{key}' exists in dictionary")
else:
print(f"No, key: '{key}' does not exists in dictionary")

④keyの値を求める関数を使用する
#存在しないkeyの場合errorを返すところを利用する
def check_key_exist(test_dict, key):
try:
value = test_dict[key]
return True
except KeyError:
return False
word_freq = {
"Hello": 56,
"at": 23,
"test": 43,
"this": 78
}
key = 'test'
if check_key_exist(word_freq, key):
print(f"Yes, key: '{key}' exists in dictionary")
else:
print(f"No, key: '{key}' does not exists in dictionary")

出典
https://thispointer.com/python-how-to-check-if-a-key-exists-in-dictionary/

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?