Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: what is best way to check multiple keys exists in a dictionary?

my dict looks like

d = {
  'name': 'name',
  'date': 'date',
  'amount': 'amount',
  ...
}

I want to test if name and amount exists, so I will do

if not `name` in d and not `amount` in d:
  raise ValueError # for example

Suppose I get the data from an api and I want to test if 10 of the fields exists in the dictionary or not.

Is it still the best way to look for?

like image 629
daydreamer Avatar asked Apr 14 '13 21:04

daydreamer


People also ask

How do you check if multiple keys exist in a dictionary Python?

isSubset() to check multiple keys exist in Dictionary The python isSubset() method returns true if all the elements of the set passed as argument present in another subset else return false.

How do you check if a key value pair exists in a dictionary Python?

To check if a key-value pair exists in a dictionary, i.e., if a dictionary has/contains a pair, use the in operator and the items() method. Specify a tuple (key, value) . Use not in to check if a pair does not exist in a dictionary.

Which operator tests to see if a key exists in a dictionary?

The simplest way to check if a key exists in a dictionary is to use the in operator. It's a special operator used to evaluate the membership of a value. This is the intended and preferred approach by most developers.

How do you check if a key does not exists in a dictionary Python?

Checking if key exists using the get() method The get() method is a dictionary method that returns the value of the associated key. If the key is not present it returns either a default value (if passed) or it returns None. Using this method we can pass a key and check if a key exists in the python dictionary.


2 Answers

You can use set intersections:

if not d.viewkeys() & {'amount', 'name'}:
    raise ValueError

In Python 3, that'd be:

if not d.keys() & {'amount', 'name'}:
    raise ValueError

because .keys() returns a dict view by default. Dictionary view objects such as returned by .viewkeys() (and .keys() in Python 3) act as sets and intersection testing is very efficient.

Demo in Python 2.7:

>>> d = {
...   'name': 'name',
...   'date': 'date',
...   'amount': 'amount',
... }
>>> not d.viewkeys() & {'amount', 'name'}
False
>>> del d['name']
>>> not d.viewkeys() & {'amount', 'name'}
False
>>> del d['amount']
>>> not d.viewkeys() & {'amount', 'name'}
True

Note that this tests True only if both keys are missing. If you need your test to pass if either is missing, use:

if not d.viewkeys() >= {'amount', 'name'}:
    raise ValueError

which is False only if both keys are present:

>>> d = {
...   'name': 'name',
...   'date': 'date',
...   'amount': 'amount',
... }
>>> not d.viewkeys() >= {'amount', 'name'}
False
>>> del d['amount']
>>> not d.viewkeys() >= {'amount', 'name'})
True

For a strict comparison (allowing only the two keys, no more, no less), in Python 2, compare the dictionary view against a set:

if d.viewkeys() != {'amount', 'name'}:
    raise ValueError

(So in Python 3 that would be if d.keys() != {'amount', 'name'}).

like image 132
Martijn Pieters Avatar answered Oct 12 '22 08:10

Martijn Pieters


if all(k not in d for k in ('name', 'amount')):
    raise ValueError

or

if all(k in d for k in ('name', 'amount')):
    # do stuff
like image 36
jamylak Avatar answered Oct 12 '22 06:10

jamylak