Only A and D are correct. Technically there can be a key which has None as its value, then option B will fail, because it checks for the presence of a value, not the key itself.
######## sample code ########
d = {'key1': 1, 'key2': None}
k = 'key2'
print(d)
if k in d:
print(f'\'{k}\' exists in dict')
else:
print(f'\'{k}\' does not exist in dict')
if k in d.keys():
print(f'\'{k}\' exists in dict')
else:
print(f'\'{k}\' does not exist in dict')
# wrong way because it check for the presence of value, not the key itself
if d.get(k) is not None:
print(f'\'{k}\' exists in dict <-- using wrong way')
else:
print(f'\'{k}\' does not exist in dict <-- using wrong way')
# wrong way because it check for the presence of value, not the key itself
if d[k] != None:
print(f'\'{k}\' exists in dict <-- using wrong way')
else:
print(f'\'{k}\' does not exist in dict <-- using wrong way')
3 of them work, I vote AD (B is a bit ugly!)
dict = {'key': 'Farts'}
try:
if 'key' in dict:
print("Key exists (A)")
if dict['key']!= None:
print("Key exists (B)")
if 'key' in dict.keys():
print("Key exists (D)")
if dict.exists ('key'):
print("Key exists (C)")
except:
pass
Key exists (A)
Key exists (B)
Key exists (D)
A&D are most Python. B also returns True but it's a check if a key isn't None and no if a key exists so I'd cut that answer first.
> dict = {'key' : 'value'}
> print('key' in dict)
True
> print(dict['key'] != None)
True
> print(dict.exists('key'))
Traceback (most recent call last):
File "./prog.py", line 4, in <module>
AttributeError: 'dict' object has no attribute 'exists'
> print('key' in dict.keys())
True
A voting comment increases the vote count for the chosen answer by one.
Upvoting a comment with a selected answer will also increase the vote count towards that answer by one.
So if you see a comment that you already agree with, you can upvote it instead of posting a new comment.
JeyTlenJey
3 months, 4 weeks agoOracleist
9 months, 3 weeks agoAcid_Scorpion
1 year, 2 months agokosa997
1 year, 4 months agoBubu3k
1 year, 5 months agomlsc01
1 year, 9 months agoNetspud
1 year, 9 months agorotimislaw
2 years agojaimebb
2 years agoDav023
2 years, 1 month agociccio_benzina
2 years, 2 months agoJnanada
2 years, 3 months agoPremJaguar
2 years, 4 months agobebi
2 years, 4 months agomacxsz
2 years, 6 months agoefemona
2 years, 6 months agoMokel
2 years, 6 months ago