63
56

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 3 years have passed since last update.

[Python]dictionary内にKeyが存在するか確認する方法

Last updated at Posted at 2017-06-04

single key

Dictionary内にKeyが存在するか確認するときはinを使う。

下記のように 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を使うとよい

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

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

multiple keys

すべてのkeyが存在するか確認する方法

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

python2.7

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

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

python3

python3 ではviewkeysがkeysになる。

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

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

両方で動くようにするにはsixを使って下記のように書く。

In [6]: import six

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

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

setを使う方法

@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

少なくとも一つkeyが存在するか確認する方法

dictionary view objectでは&を使ってintersectionが取れる。
https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects

python2.7

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

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

python3

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

参考:
https://stackoverflow.com/questions/16004593/python-what-is-best-way-to-check-multiple-keys-exists-in-a-dictionary
https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects

63
56
4

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
63
56

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?