r/learnpython 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?

5 Upvotes

9 comments sorted by

4

u/atarivcs 1d ago
point_value = alien_0.get('points', 'No point value assigned.')

This code says:

  1. Get the points value for alien0.
  2. If alien0 does not have any points, use the default value 'No point value assigned'.

2

u/kforkerro 1d ago

Thanks. I was confused at first. So, latter is added to replace the message 'None' if the key doesn't exist, isn't it?

5

u/Outside_Complaint755 1d ago

If the string "No point value assigned." were not passed to get, then get(key) would return the value None, which is a special value in Python.

  Using get to return a message like this is non-standard usage.

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

u/NerdyWeightLifter 7h ago

Use : If my_key in my_dict:

To tell if a key is in a duct.