Programming Essentials Python - Overview of Collections - Accessing Elements - dict

Let us see how we can access elements from the dict using Python as a programming language.

  • We can access a value of a particular element in dict by passing the key d[key]. If the key does not exist, it will throw a KeyError.

  • The get method can also be used to access a value of a particular element in dict by passing the key as an argument. However, if the key does not exist, it will return None.

  • We can also pass a default value to get.

  • By using keys, we can get all the keys in the form of a set-like object, and by using values, we can get all the values in the form of a list-like object.

  • The items method can be used to convert a dict into a set-like object with pairs. Each element (which is a pair) in the set-like object will be a tuple.

Let us see a few examples.

# Creating a dict object
d = {'id': 1, 'first_name': 'Scott', 'last_name': 'Tiger', 'amount': 1000.0}

# Accessing one of the elements with the key **id** from `dict`.
d['id']

# Accessing another element with the key **first_name** from `dict`.
d['first_name']

# This will throw a key error as the key does not exist.
d['commission_pct']

# Using `get` to get the value by passing the key as an argument.
d.get('first_name')

# If the key does not exist, it will return `None`.
d.get('commission_pct')

# You can pass a default value as the second argument to `get`.
d.get('first_name', 'Some First Name')
d.get('commission_pct', 0)

# Getting all the keys in a set-like object (as keys are unique)
d.keys()

# Getting all the values in a list-like object.
d.values()

# Getting all the items in a set-like object.
# Each item will be of type tuple.
# Each tuple will contain key from the dict followed by the corresponding value.
d.items()

# We can convert keys, values, or items to a list and perform any list operations.
list(d.items())[0]  # First tuple from the list of items from dict
list(d.items())[1]  # Second tuple from the list of items from dict
type(list(d.items())[1])

Hands-On Tasks

To practice accessing elements from a dictionary in Python, you can try the following tasks:

  1. Create a dictionary with at least 5 key-value pairs and access each value by passing its key.
  2. Use the get method to retrieve a value by passing the key and provide a default value if the key does not exist.

Conclusion

In this article, we have covered how to access elements from a dictionary (dict) in Python. Understanding how to retrieve values using keys and methods like get is essential for working with dictionaries effectively. Practice the hands-on tasks to reinforce your learning, and don’t hesitate to engage with the community for further support.

Click here to watch the video tutorial on accessing elements from a dictionary in Python.

Watch the video tutorial here