How to Check That Multiple Keys Are in a Dict in a Single Pass

How do I check that multiple keys are in a dict in a single pass?

Well, you could do this:

>>> if all(k in foo for k in ("foo","bar")):
... print "They're there!"
...
They're there!

How to get multiple dictionary values?

Use a for loop:

keys = ['firstKey', 'secondKey', 'thirdKey']
for key in keys:
myDictionary.get(key)

or a list comprehension:

[myDictionary.get(key) for key in keys]

python: what is best way to check multiple keys exists in a 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'}).

checking multiple keys in a dictionary is not working. python

The expression ("redshift" and "host") in config[name] does not test if both keys are present.

("redshift" and "host") produces just "host", because and returns either the first expression if false according to its truth value, otherwise the second expression is returned. So in the end, all you are really testing is the expression "host" in config[name].

Use two separate in tests:

if "redshift" in config[name] and "host" in config[name]:

or test for with a set against the dictionary with set.issubset():

if {'redshift', 'host'}.issubset(config[name]):

Check if list of keys exist in dictionary

Use all():

if all(name in grades for name in students):
# whatever

Is it possible to assign the same value to multiple keys in a dict object at once?

I would say what you have is very simple, you could slightly improve it to be:

my_dict = dict.fromkeys(['a', 'c', 'd'], 10)
my_dict.update(dict.fromkeys(['b', 'e'], 20))

If your keys are tuple you could do:

>>> my_dict = {('a', 'c', 'd'): 10, ('b', 'e'): 20}
>>> next(v for k, v in my_dict.items() if 'c' in k) # use .iteritems() python-2.x
10

This is, of course, will return first encountered value, key for which contains given element.



Related Topics



Leave a reply



Submit