LoginSignup
2
2

More than 5 years have passed since last update.

any()を使って、list内の特定のdict要素の有無をbool値で返す

Last updated at Posted at 2017-11-15
dict_list = [{'name': 'name1', 'value': True}, {'name': 'name2', 'value': True}, {'name': 'name3', 'value': 'hogehoge'}]

上記のようなdict要素を持っているlistがあるとして、'name'が'name3'のものがあるかをbool値で返したかったんだけれど、以下のようにany()でやるのが一番楽っぽい気がする

any(dict_item['name'] == 'name3' for dict_item in dict_list)
# True

any(dict_item['name'] == 'name4' for dict_item in dict_list)
# False

他に楽な方法あるかな


ちなみにこういう感じで、dictのkeyが異なるようだと使えないので、listに型が異なるdict要素が入る場合はなんか別の方法でやる必要がある

dict_list = [{'wwww': 'name1', 'value': True}, {'namefaefe': 'nam2', 'value': True}, {'name': 'name3', 'value': 'hogehoge'}]

any(dict_item['name'] == 'name3' for dict_item in dict_list)
# Traceback (most recent call last):
#  File "<stdin>", line 1, in <module>
#  File "<stdin>", line 1, in <genexpr>
# KeyError: 'name'

KeyErrorなので、辞書のgetメソッドを使うと大丈夫そうです

any(dict_item.get('name') == 'name3' for dict_item in dict_list)
# True
2
2
3

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
2
2