Well, you could do this:
>>> if all(k in foo for k in ("foo","bar")):
... print "They're there!"
...
They're there!
Answer from hughdbrown on Stack OverflowWell, you could do this:
>>> if all(k in foo for k in ("foo","bar")):
... print "They're there!"
...
They're there!
if {"foo", "bar"} <= myDict.keys(): ...
If you're still on Python 2, you can do
if {"foo", "bar"} <= myDict.viewkeys(): ...
If you're still on a really old Python <= 2.6, you can call set on the dict, but it'll iterate over the whole dict to build the set, and that's slow:
if set(("foo", "bar")) <= set(myDict): ...
Most Python way to check if one or multiple keys match in a dictionary?
python - Check if dictionary has multiple keys - Stack Overflow
python: what is best way to check multiple keys exists in a dictionary? - Stack Overflow
Check multiple `keys` in Python dictionary - Stack Overflow
Hello Reddit,
For a single key to match it very easy to check of the key is available:
if "keyname" in mydict:
#do something with if this key matches
To check if multiple keys are in the dict:
if {"keyname1", "keyname2"}.issubset(mydict):
#do something if both are in the dict
What I want is to check if one or two are in the dict:
if "keyname1" or "keyname2" in dict:
#this will not work as it will check:
# ("keyname1") or ("keyname2" in dict) and not
# ("keyname1" or "keyname2") in dict
#do something if one or more of them matchesHow do I achieve this?
Use the builtin function all()
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> keys = ('a', 'b')
>>> all(elem in d for elem in keys)
True
>>> keys = ('a', 'b', 'd')
>>> all(elem in d for elem in keys)
False
You may also try like this:
>>> names = {
'a' : 11,
'b' : 10,
'c' : 14,
'd': 7
}
>>> keys = ('a', 'b')
>>> set(keys).issubset(names)
True
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
Here's one way to do it without having to use .items():
for obj in listofobjs:
if 'tel' in obj and 'nam' in obj and obj['tel']==tel and obj['nam']==nam:
...
Or you could ask for forgiveness provided all dictionary access in the if block are safe:
for obj in listofobjs:
try:
if obj['tel']==tel and obj['nam']==nam:
...
except KeyError:
pass
You don't need to loop over the .items() to do this.
for obj in listofobjs:
if (obj.get('tel', None) == tel) and (obj.get('nam', None) == nam):
Just use .get to get the key, so that you don't get a KeyError if the key doesn't exist.
.get returns None by default, but I'm specifying it here to highlight the ability to use a different default value. If you want to use None as the default, you can leave out the second parameter from the .get call.
Replace None with a value that you know will never be a valid value for tel or nam.