Help us understand the problem. What is going on with this article?


single key


下記のように key in dict.keys() 又は key in dictどちらでもよい。

In [2]: D = {'abc': 1, 'def': 2, 'ghi': 3, 'jkl' : 4}

In [3]: 'abc' in D.keys()
Out[3]: True

In [4]: 'xyz' in D.keys()
Out[4]: False

In [5]: 'abc' in D
Out[5]: True


In [6]: 1 in D.values()
Out[6]: True

In [7]: 5 in D.values()
Out[7]: False

multiple keys


複数のkeyが存在するか確認するときはDictionary view objectを使う。python2.7とpython3系でDictonary view objectの取得方法が変わっている。python2.7の時はviewkeys()をpython3の時はkeys()を使う。


In [8]: D.viewkeys() >= {'abc', 'def'}
Out[8]: True

In [9]: D.viewkeys() >= {'abc', 'xyz'}
Out[9]: False


python3 ではviewkeysがkeysになる。

In [3]: D.keys() >= {'abc', 'def'}
Out[3]: True

In [4]: D.keys() >= {'abc', 'xyz'}
Out[4]: False


In [6]: import six

In [7]: six.viewkeys(D) >= {'abc', 'def'}
Out[7]: True

In [8]: six.viewkeys(D) >= {'abc', 'xyz'}
Out[8]: False


@shiracamus さんからコメントで教えてもらった方法。こちらだとsixをimportする必要が無くすっきりしてます。

In [21]: set(D) >= {'abc', 'def'}
Out[21]: True

In [22]: set(D) >= {'abc', 'xyz'}
Out[22]: False

for loop & all を使う方法

@shiracamus さんからコメントで教えてもらった方法。

In [2]: all(key in D for key in ('abc', 'def'))
Out[2]: True

In [3]: all(key in D for key in ('abc', 'xyz'))
Out[3]: False


dictionary view objectでは&を使ってintersectionが取れる。


In [14]: len(D.viewkeys() & {'abc', 'xyz'}) > 0
Out[14]: True

In [15]: len(D.viewkeys() & {'x', 'xyz'}) > 0
Out[15]: False


In [10]: len(D.keys() & {'abc','xyz'}) > 0
Out[10]: True

In [11]: len(D.keys() & {'x','xyz'}) > 0
Out[11]: False

for loop & anyを使う方法

@shiracamus さんからコメントで教えてもらった方法。

In [25]: any(key in D for key in ('abc', 'xyz'))
Out[25]: True

In [26]: any(key in D for key in ('abc', 'def'))
Out[26]: True

In [27]: any(key in D for key in ('x', 'xyz'))
Out[27]: False


Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away