+1 vote
in GK Quiz QA by (71.8k points)
What is the Pythonic way to return a value when some key is not present in a dictionary?

1 Answer

+2 votes
by (73.8k points)
selected by
 
Best answer

You can use the get() method of the dictionary. It returns the value if a given key is present in the dictionary. If the key is not present, it returns None. However, you can set your desired value in case the key is not found.

Here is an example. I am returning -1 if the key is not present.

>>> aa

{'a': 11, 'b': 12, 'c': 13}

>>> aa.get('a')

11

>>> aa.get('x', -1)

-1

>>> aa.get('a', -1)

11

Since 'x' is not a key, it returned -1.

...