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?
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.
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.
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.
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.
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'}
).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With