Skip to content
Home » Dictionary Methods – get

Dictionary Methods – get

Spread the love

In one of my previous articles we were talking about the pop and popitem dictionary methods. Today we’ll be talking about the get method.

Here’s the video version of the article:

The method get(key) may be used to access the value corresponding to key. It works like the [] operator if the key is found. Let’s define a dictionary:

>>> locations = {"Mexico" : "North America", "Chile" : "South America", "Estonia" : "Europe", "China" : "Asia"}

First let’s access one of its elements using square brackets:

>>> locations["Chile"]
'South America'

The same can be achieved by means of the get method:

>>> locations.get("Chile")
'South America'

If the key is not found, the [] operator raises an error whereas get returns None:

>>> locations["Peru"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Peru'

>>> locations.get("Peru")
>>> print(locations.get("Peru"))
None

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Default Value

There is also a version with 2 parameters: get(key, value). We can use it to set a default value, which will be returned, if the key is not found.

>>> locations.get("Peru", "South America")
'South America'

If the key is found, the method get(key, value) will not return the value from the parameter, but the one from the dictionary:

>>> locations.get("Estonia", "North America")
'Europe' 

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply