Prevent KeyError when working with dictionaries in Python
Python tip:
You can use
.get()
to avoid a KeyError when accessing non-existing keys inside a dictionary:user = {"name": "Jan", "surname": "Giacomelli"} print(user.get("address", "Best street 42")) # => Best street 42 print(user["address"]) # => KeyError: 'address'
If you don't provide a default value,
.get()
will returnNone
if the key doesn't exist.If you're just trying to see if the key exists, it's better to use the
in
operator like so due to performance reasons:# good if "address" in user: print("yay") else: print("nay") # bad if user.get("address"): print("yay") else: print("nay")