python
[Python] The get() method on Python dicts and its "default" arg
# The get() method on dicts
# and its "default" argument
name_for_userid = {
382: "Alice",
590: "Bob",
951: "Dilbert",
}
def greeting(userid):
return "Hi %s!" % name_for_userid.get(userid, "there")
>>> greeting(382)
"Hi Alice!"
>>> greeting(333333)
"Hi there!"
''' When "get()" is called it checks if the given key exists in the dict.
If it does exist, the value for that key is returned.
If it does not exist then the value of the default argument is returned instead.'''
Was this helpful?
Similar Posts
- [Python] Use json.dumps() to pretty-print Python dicts
- Get string length using len() method python
- Remove an item from python list using its index
- Get payment method response from strip
- [Python] Default value of function argument
- Use separator in print() method of python
- Add column to existing table with default value SQLAlchemy