How do you check the presence of many keys in a Python dictionary?
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开发者_如何学Go number of keys in a very big dictionary?
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
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
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
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.
精彩评论