Check If Key Exists And Get The Value At The Same Time In Python?
Solution 1:
If the situations with missing values are really exceptional then the exception handling is appropriate:
try:
value = my_dict[key]
# Do somethingexcept KeyError:
pass
If both missing and present keys are to be handled then your first option is useful.
ifkeyin my_dict:
value = my_dict[key]
# Do something
The use of get
doesn't provide any advantage in this specific situation. In contrary, you have to find a non-conflicting value to identify the missing key condition.
Solution 2:
As mentioned several times, exception handling is the way to go. However, if you want to use get
and None
is a possible value, create a new object to act as the "not found" sentinel. (Since you've just created the object, it's impossible for it to be a valid entry in your dict
. Well, not impossible, but you would really have to go out of your way to add it to the dict
.)
sentinel = object()
value = my_dict.get(key, sentinel)
if value isnot sentinel:
# Do something with value
Solution 3:
if (dict.get('key') isnotNone) and ('key'indict):
var = dict['key']
Second portion of if-statement may not be totally necessary but I have used this format in my own code and it does the job.
Post a Comment for "Check If Key Exists And Get The Value At The Same Time In Python?"