(Day 09) Task : Dictionaries and Nesting in Python :-

Aditya SharmaAditya Sharma
5 min read

Python is known for its simplicity and powerful data structures. One such essential and flexible data structure is the dictionary. In this article, we will explore what dictionaries are, how they are used, and how nesting enhances their capabilities, with detailed examples.

What is a Dictionary in Python?

A dictionary in Python is an unordered, mutable, and indexed collection of items. Each item in a dictionary is a pair of key and value, written as key: value. Dictionaries are defined using curly braces {}.

my_dict = {
    "name": "Alice",
    "age": 25,
    "is_student": True
}

Key Characteristics:

  • Keys must be unique.

  • Values can be duplicated.

  • Keys must be immutable types (like strings, numbers, or tuples).

Common Dictionary Operations :-

Creating a Dictionary :

person = {"name": "John", "age": 30}

Explanation:

  • A dictionary is created using curly braces {}.

  • Each item consists of a key (e.g., "name") and a value (e.g., "John").

  • In this case, the dictionary has two key-value pairs: "name" and "age".

Accessing Values :

print(person["name"])  # Output: John

Explanation:

  • Use square brackets [] with the key to access its corresponding value.

  • If the key exists, it returns the value.

  • If the key does not exist, it raises a KeyError.

Adding or Updating Values :

person["email"] = "john@example.com"
person["age"] = 31

Explanation:

  • Adding a new key-value pair is as simple as assigning a value to a new key.

  • Updating an existing key's value is done by reassigning it.

Removing Items :

del person["age"]         # Deletes 'age'
person.pop("email")       # Also deletes 'email'

Explanation:

  • del deletes a key-value pair permanently.

  • pop() removes a key and returns its value. Raises KeyError if the key doesn’t exist.

  • if you're unsure whether the key exists, prefer pop("key", default_value) or use if "key" in dict: before removing.

Checking Keys :

"name" in person  # Returns True

Explanation:

  • This checks if a key ("name") exists in the dictionary.

  • Returns True or False.

Iterating Through a Dictionary :

for key, value in person.items():
    print(key, value)

Explanation:

  • .items() returns a view of key-value pairs.

  • This allows you to loop over both keys and values in a dictionary.

Create an Empty Dictionary :

Method 1: Using curly braces {} :

my_dict = {}

Explanation:

  • This is the simplest and fastest way to create an empty dictionary.

  • It's readable and widely used.

Method 2: Using the dict() constructor :

my_dict = dict()

Explanation:

  • This uses Python’s built-in dict() function.

  • It's useful when you want to create a dictionary programmatically (e.g., from a list of tuples or with keyword arguments).

Erase or wipe an existing Dictionary :

In Python, a dictionary is a mutable data structure, so it can be changed or cleared at any time. Sometimes you may want to remove all data from a dictionary. There are several ways to do this, depending on your use case.

Method 1: Using .clear() :

my_dict = {"name": "Alice", "age": 25}
my_dict.clear()
print(my_dict)  # Output: {}

Explanation:

  • The .clear() method removes all key-value pairs from the dictionary.

  • The variable my_dict still exists, but now it is an empty dictionary.

  • This is the recommended method when you want to reuse the same dictionary object but clear its contents.

Use Case:

  • When you're working with a dictionary that is passed to a function and you want to reset it without changing the reference.

Method 2: Reassign to an Empty Dictionary :

my_dict = {"name": "Alice", "age": 25}
my_dict = {}
print(my_dict)  # Output: {}

Explanation:

  • This creates a new empty dictionary and assigns it to the variable my_dict.

  • The original dictionary is discarded, and the variable now refers to a new empty object.

  • Old data is garbage collected if no other variable is referencing it.

Use Case:

  • When you want to completely reset the dictionary and don’t need to preserve the original object reference.

Method 3: Using del to Delete the Dictionary :

my_dict = {"name": "Alice", "age": 25}
del my_dict

Explanation:

  • The del keyword deletes the variable itself from memory.

  • Once deleted, the variable no longer exists, and trying to access it will raise a NameError.

Use Case:

  • When you want to completely remove the dictionary and free up memory.

  • Useful in large-scale programs where memory management is critical.

Nesting in Dictionaries :-

Nesting means storing a dictionary inside another dictionary, or using lists or tuples as values within a dictionary. This is especially useful when handling structured data like JSON, database records, or API responses.

1. Dictionary Inside a Dictionary :

students = {
    "101": {"name": "Alice", "marks": 85},
    "102": {"name": "Bob", "marks": 90},
    "103": {"name": "Charlie", "marks": 78}
}

print(students["102"]["name"])  # Output: Bob

Real-World Example:

inventory = {
    "laptop": {"brand": "Dell", "stock": 10, "price": 70000},
    "mouse": {"brand": "Logitech", "stock": 50, "price": 500}
}

2. List Inside a Dictionary :

student = {
    "name": "David",
    "courses": ["Math", "Science", "History"]
}
print(student["courses"][1])  # Output: Science

This approach is useful for storing multiple values under a single key.

3. Dictionary Inside a List :

This pattern is common when working with records of similar structure.

employees = [
    {"name": "John", "role": "Manager"},
    {"name": "Sara", "role": "Developer"}
]

print(employees[0]["role"])  # Output: Manager

When to Use Nesting

  • When you need to represent complex hierarchical data.

  • When working with JSON (JavaScript Object Notation) from web APIs.

  • When modeling real-world entities (like students, products, or users).

Project Blind Auction Program :-

https://appbrewery.github.io/python-day9-demo/ ——> Demo You can try.

OUTPUT :

0
Subscribe to my newsletter

Read articles from Aditya Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aditya Sharma
Aditya Sharma

DevOps Enthusiast | Python | Chef | Docker | GitHub | Linux | Shell Scripting | CI/CD & Cloud Learner | AWS