Accessing values of a dictionary

Download python eBook


dictionary = {"Hello": 1234, "World": 5678}

The above code will print 1234.

The string "Hello" in this example is called a key. It is used to lookup a value in the dict by placing the key in square brackets.

The number 1234 is seen after the respective colon in the dict definition. This is called the value that "Hello" maps to in this dict.

Looking up a value like this with a key that does not exist will raise a KeyError exception, halting execution if uncaught. If we want to access a value without risking a KeyError, we can use the dictionary.get method. By default if the key does not exist, the method will return None. We can pass it a second value to return instead of None in the event of a failed lookup.

w = dictionary.get("whatever")
x = dictionary.get("whatever", "nuh-uh")

In this example w will get the value None and x will get the value "nuh-uh".


Contributors: 5
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial:

Download eBook