tags:

views:

176

answers:

4

I have the following dictionary:

sites = {
    'stackoverflow': 1,
    'superuser': 2,
    'meta': 3,
    'serverfault': 4,
    'mathoverflow': 5
}

To check if there are more than one key available in the above dictionary, I will do something like:

'stackoverflow' in sites and 'serverfault' in sites

The above is maintainable with only 2 key lookups. Is there a better way to handle checking a large number of keys in a very big dictionary?

+9  A: 

You could use all:

print( all(site in sites for site in ('stackoverflow','meta')) )
# True
print( all(site in sites for site in ('stackoverflow','meta','roger')) )
# False
unutbu
+1 for all and the generator expression, but -1 for extra parens on `(_ in sites)` and for using `_` as your variable name. I realize that whatever you use is a throwaway variable, but `_` as a variable name somehow just slows down my comprehension. Why not just `all(s in sites for s in ('stackoverflow','meta'))`. This actually has an advantage over the set-based solution in that it is not necessary to build a set of the long list of sites to check, and `all` will short-circuit as soon as the first mismatch is found.
Paul McGuire
@Paul, thanks for your comment. What can I say, but, I agree!
unutbu
+1 for your perceptive judgment of technical merit!
Paul McGuire
A: 

How many lookups are you planning to do? I think the method you are using is fine.

If there are dozens, hundreds, etc of keys you are comparing against you could put all of the target keys in a list and then iterate over the list, checking to make sure each item is in the dictionary.

Justin Ethier
+11  A: 

You can pretend the keys of the dict are a set, and then use set.issubset:

set(['stackoverflow', 'serverfault']).issubset(sites) # ==> True

set(['stackoverflow', 'google']).issubset(sites) # ==> False
Andrew Jaffe
+1  A: 
mysites = ['stackoverflow', 'superuser']
[i for i in mysites if i in sites.keys()]  # ==> sites in the list mysites that are in your dictionary
[i for i in mysites if i not in sites.keys()]  # ==> sites in the list mysites that are not in your dictionary
inspectorG4dget
You don't need the `.keys()` and probably shouldn't use it. It creates a list that you don't need and changes your `in` statement to O(n) instead of O(1) without it. Besides that, this is a very readable way to get a lists of which sites are (not) part of the dictionary.
tgray