In Python How Do You Avoid the Inelegant Dictionary Key-Check Logic?

Problem scenario
You try this

book = {}
book["apple"] = 5
var1 = book["orange"]

It returns this:

Traceback (most recent call last):
File "", line 3, in
var1 = book["orange"]
KeyError: 'orange'

You often see a couple lines of code check if a key exists in a dictionary before a specific action. You want to avoid this and write Python in a more elegant fashion. What do you do?

Use the .get() method.

Try this

book = {}
book["apple"] = 5
var1 = book.get("orange")

It returns nothing. There are no errors. (You could then print var1 to view the contents.)

Leave a comment

Your email address will not be published. Required fields are marked *