Programming Essentials Python - Overview of Collections - Common Examples - dict

In this article, we will explore the concept of creating a dictionary in Python. The following sections will break down the key concepts and provide hands-on tasks for better understanding.

Explanation for the video

[Embedded YouTube Video Placeholder]

Key Concepts Explanation

Key Concept 1

A dictionary in Python consists of key-value pairs where the key can be of any type and the value can be of any type. Typically, we use attribute names as keys in a dictionary, which are of type str.

# Creating a dictionary with key-value pairs
d = {'id': 1, 'first_name': 'Scott', 'last_name': 'Tiger', 'amount': 1000.0}

Key Concept 2

The value in a dictionary can be of simple types such as int, float, or str, or it can be an object of a custom type. Additionally, the value can also be a list or a nested dictionary.

# Adding a list as a value in the dictionary
d.update([('phone_numbers', [1234567890, 2345679180])])

# Adding a nested dictionary as a value in the dictionary
d['address'] = {'street': '1234 ABC Towers', 'city': 'Round Rock', 'state': 'Texas', 'zip': 78664}

Hands-On Tasks

Explore the following tasks to practice creating dictionaries in Python:

  1. Create a dictionary with your personal information as key-value pairs.
  2. Add a list of hobbies as a value in the dictionary.
  3. Create a nested dictionary for your home address details.

Conclusion

In summary, dictionaries in Python are versatile data structures that allow you to store key-value pairs efficiently. Practice creating dictionaries with different types of values to get a better understanding of how they work.

Common Examples - dict

Let us see some common examples while creating dict in Python. If you are familiar with JSON, dict is similar to JSON.

  • A dict can have key value pairs where key is of any type and value is of any type.

  • However, typically we use attribute names as keys for dict. They are typically of type str.

  • The value can be of simple types such as int, float, str etc or it can be object of some custom type.

  • The value can also be of type list or nested dict.

  • An individual might have multiple phone numbers and hence we can define it as list.

  • An individual address might have street, city, state and zip and hence we can define it as nested dict.

  • Let us see some examples.

# Sample examples of creating and working with dictionaries
# Code examples as provided above

Watch the video tutorial here