Python

In Python, a Dictionary is a built-in data structure that stores data in key-value pairs. Unlike lists or tuples, which use positional indexing, dictionaries use keys to look up values, making them incredibly fast for retrieving data.

As of Python 3.7+, dictionaries are ordered (they remember the order in which items were inserted).

1. Theoretical Overview

Characteristics of Dictionaries

  • Key-Value Pair: Each entry is a map between a unique "Key" and its associated "Value."

  • Unique Keys: Keys must be unique within a single dictionary. If you assign a value to an existing key, the old value is overwritten.

  • Immutable Keys: Keys must be of an immutable data type (strings, numbers, or tuples). Values, however, can be any data type.

  • Fast Lookup: Dictionaries use a technique called Hashing, which allows Python to find a value almost instantly, even if the dictionary contains millions of items.

Why Use a Dictionary?

  • Representing Real-world Objects: Perfect for storing structured data like a user profile (name, age, email).

  • Efficiency: Finding an item by key is much faster than searching through a list.

  • Mapping: Useful for creating "lookup tables" (e.g., mapping country codes to country names).

2. Basic Syntax and Creation

Dictionaries are defined using curly braces {} with keys and values separated by colons :.

Python
# Creating a dictionary
student = {
    "name": "Arjun",
    "age": 21,
    "course": "Python Programming",
    "is_enrolled": True
}

print(student["name"])  # Output: Arjun

3. Key Dictionary Operations

A. Accessing and Modifying

You can access a value by referring to its key name. If the key doesn't exist, it throws a KeyError (unless you use the .get() method).

Python
# Accessing with .get() (safer)
course = student.get("course")
rank = student.get("rank", "Not Assigned") # Returns default value if key missing

# Updating a value
student["age"] = 22

# Adding a new key-value pair
student["email"] = "arjun@example.com"

B. Removing Items

MethodDescriptionExample
pop()Removes the item with the specified key name.student.pop("age")
popitem()Removes the last inserted item.student.popitem()
delKeyword that removes an item or the whole dictionary.del student["name"]
clear()Empties the entire dictionary.student.clear()

C. Looping through Dictionaries

You can loop through keys, values, or both simultaneously.

Python
# Loop through keys
for key in student:
    print(key)

# Loop through values
for val in student.values():
    print(val)

# Loop through both (Items)
for key, value in student.items():
    print(f"{key}: {value}")

4. Built-in Dictionary Methods

Python provides essential methods for dictionary management:

Python
# Get all keys
print(student.keys())   # dict_keys(['name', 'course', ...])

# Get all values
print(student.values()) # dict_values(['Arjun', 'Python', ...])

# Update dictionary with another dictionary
student.update({"age": 23, "city": "Dehradun"})

5. Nested Dictionaries

A dictionary can contain other dictionaries as values. This is common in API responses (JSON format).

Python
employees = {
    "emp1": {"name": "Sanya", "year": 2022},
    "emp2": {"name": "Rohan", "year": 2024}
}

print(employees["emp1"]["name"]) # Output: Sanya
Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now