+ 2
Can we do boolean on dictionary keys?
For example i want to check whether 'a' key is in dict or not. what should i do? so far i did this : a = {'123':0,'445':0} if a['567'] in a: print('yes') else: print('no') and it returns a key error
2 Respostas
+ 3
you should use .get method.
for example, in your dictionary
value=a.get('567','not in dictionary')
if '567' is in dictionary, value would be similar to a['567']. The second argument is returned by get method if element is not in dictionary.
Then you can apply boolean on value returned.
if value=='not in dictionary':
print('no')
else:
print('yes')
Another way which similar to what you've tried is using dictionary.keys()
ie
if '567' in a.keys():
print('yes')
else:
print('no')
+ 3
more on what Akash said:
if '567' in a.keys():
print('yes')
else:
print('no')
in this example you don't need to write a.keys(). 'in' tests keys in a dict by default, the example can be rewritten like this:
if '567' in a:
print('yes')
else:
print('no')
you can directly write the expression in the print if you wish so
print('567' in a)