The answer will be A, D
Why?
dict = {'a': 1, 'b': None}
# Works
if 'a' in dict:
print('yes')
# Checks if the value is not None [The key could have value None]
# Will fail for key 'b' as value is None
# We have to cheque for if a key is present or not
if dict['a'] != None:
print('yes')
print(dict['a'] != None)
# AttributeError: 'dict' object has no attribute 'exists'
# if dict.exists('a'):
# print('yes')
# Works
if 'a' in dict.keys():
print('yes')
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.
okg
3 weeks, 5 days agoJeyTlenJey
7 months, 2 weeks agoOracleist
1 year, 1 month agoAcid_Scorpion
1 year, 5 months agokosa997
1 year, 7 months agoBubu3k
1 year, 9 months agomlsc01
2 years agoNetspud
2 years agorotimislaw
2 years, 3 months agojaimebb
2 years, 4 months agoDav023
2 years, 5 months agociccio_benzina
2 years, 6 months agoJnanada
2 years, 6 months agoPremJaguar
2 years, 7 months agobebi
2 years, 8 months agomacxsz
2 years, 10 months agoefemona
2 years, 10 months ago