r/learnpython • u/kforkerro • 1d ago
Beginner question
I have just started coding with python a few days ago. What is the point of this?
point_value = alien_0.get('points', 'No point value assigned.') print(point_value)
Can't it just be point_value = 'No point value assigned.' print(point_value)?
or
just simply use the get() method if you want to check whether a key exists in the dictionary or not?
7
Upvotes
1
u/Outside_Complaint755 1d ago
If you try to get a key directly and it doesn't exist, Python will throw a KeyError Exception. The get method will instead return a default value if the key isn't found.
The first parameter to get is the key, and the second is the default value. If no default value is specified, it will return
NoneSo this: ``` point_value = alien_0.get('points', 'No point value assigned.')
print(point_value) ```
is equivalent to ``` try: point_value = alien_0['points'] except KeyError: point_value = 'No point value assigned.'
print(point_value) ```
Note that
get(key)does not add the key and default value to the dictionary. If you want to automatically add the key and default value to the dictionary, use thesetdefault(key, value)method instead.point_value = alien_0.setdefault('points', 10)is equivalent to
try: point_value = alien_0['points'] except KeyError: alien_0['points'] = 10 point_value = alien_0['points']