Monday, January 28, 2019

Python Tricks: Dictionary Tricks


Dictionary Default Values:

Easier to ask for forgiveness than permission ( EAFP )

def greeting ( userid ):
    return 'Hi %s!' % name_for_userid.get(userid, 'there')

When get() is called, it checks if the given key exists in the dictionary. If it does, the value for the key is returned. If it does not exist, then the value of the default parameter is returned instead. 

No comments:

Post a Comment