Question
In this exercise, the get()
method return is assigned to a variable even if nothing is return. Is it possible to use the method without assigning the result to a variable?
Answer
Yes, you can use the get()
method without assigning the result to a variable. In that case, it would function more like an alternative to checking for a key using in
. The following code example shows the use of the get()
method as part of an if
to check whether a key exists in the dictionary and then the same check using the more conventional in
style. Both produce the same result - the print()
function is called to report that “Data was not found”.
directions = { "North": 10, "South": 5, "East": 20, "West":40 }
if directions.get('NorthWest'):
print("Data exists")
else:
print("Data was not found")
if 'NorthWest' in directions:
print("Data exists")
else:
print("Data was not found")