The syntax for get() method −

dict.get(key, default=None)
# The get() method on dicts and tis "default" arguement
user_id_name = {
 382: "Sange",
 590: "Cristal",
 951: "Athan",
 3821: "Sadit",
 5901: "Fina",
 9511: "Alimah",
 3822: "Farah",
 5902: "Alinafe",
 9512: "Mphasto",
 3823: "Grace",
 5903: "Tinyade",
 9513: "Tony",
 3824: "Shirley",
 5904: "Arianna",
}

# This function user_lookup() returns a greeting for a user

def user_lookup(userid):
 return "This user %s in the system!" % user_id_name[userid]

# run with an existing and non-existing value
print(user_lookup(382))

# This user Sange in the system!

print(user_lookup(123))
# Traceback (most recent call last):
# File "<input>", line 1, in <module>
# File "<input>", line 2, in the user_lookup
# KeyError: 123

# modify function to counter act the error in the last output


def user_lookup(userid):
 if userid in user_id_name:
 return "This user %s is in the system!" % user_id_name[userid]
 else:
 return "User Missing from system!"

# This function user_lookup() sets a default value using the get() method


def user_lookup_get(user_id):
 return "This user %s in the system!" % user_id_name.get(user_id, "does not exist")

print(user_lookup_get(382))
This user Sange in the system!

print(user_lookup_get(123))
This user does not exist in the system!
Advertisements