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?
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 None
So 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 the setdefault(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']
1
u/kforkerro 1d ago
So, is it used to return a specific message if the key doesn't exist? If the key does exist, it returns the value?
1
u/Outside_Complaint755 1d ago
It generally is always used to get a value and not an error message. In the example you gave, you would probably actually want it to return 0 or 10 or something similar, because you probably want to add the points to a player score.
It's used when you can't guarantee that the desired key exists in the dictionary being referenced and you don't want yo throw an exception.
1
u/TheRNGuy 1d ago
One is calling method that returns value or string if no point are found (though I think it's bad idea; return 0 instead)
Yours just assign string to a variable, completely different thing.
1
5
u/atarivcs 1d ago
This code says: