pythondictionary

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


I want to do something like:

foo = {
    'foo': 1,
    'zip': 2,
    'zam': 3,
    'bar': 4
}

if ("foo", "bar") in foo:
    #do stuff

How do I check whether both foo and bar are in dict foo?


Solution

  • Well, you could do this:

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