How to Get Value from a Dictionary in Python

In Python, one of the most useful data structures is the dictionary. The dictionary in Python is a type of mutable, changeable, unordered collection of unique elements that are stored like a map. This tutorial will guide you through the process of getting a value from a dictionary in Python.

Step 1: Understanding Python Dictionaries

A Python dictionary pairs each key with a corresponding value and it allows for the efficient retrieval of the value when you know the key. This key-value pair provides a useful way to store data. To understand better how dictionaries work, here is an example:

This dictionary, named dict_example, contains three key-value pairs. The keys are “name”, “age”, and “city”, and they each have a corresponding value: “John”, 25, and “New York”.

Step 2: Accessing Values in a Dictionary

In order to access a value in a dictionary, you pass the relevant key into the square brackets as shown below:

This will give you the age of the person in the dictionary:

25

Step 3: Using the Get() Method

Another way to access a value in Python is by using the get() method. This works in a similar way to the square bracket syntax but with one important difference: if a key is not present in the dictionary, the square brackets will raise an error, while the get() method will return None.

The code above will not raise an error, even though there is no “address” key in the dictionary. The get() method will instead return None.

Output:

25
None

Conclusion

Dictionaries are versatile and useful data structures and knowing how to extract data from them is a key skill when programming in Python. This tutorial showed how to retrieve values from a dictionary either by using the key in square brackets or by using the get() method. Both methods are useful depending on specific use cases and the type of data you are dealing with.