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).
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.
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).
Dictionaries are defined using curly braces {} with keys and values separated by colons :.
# Creating a dictionary student = { "name": "Arjun", "age": 21, "course": "Python Programming", "is_enrolled": True } print(student["name"]) # Output: Arjun
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).
# 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"
| Method | Description | Example |
| pop() | Removes the item with the specified key name. | student.pop("age") |
| popitem() | Removes the last inserted item. | student.popitem() |
| del | Keyword that removes an item or the whole dictionary. | del student["name"] |
| clear() | Empties the entire dictionary. | student.clear() |
You can loop through keys, values, or both simultaneously.
# 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}")
Python provides essential methods for dictionary management:
# 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"})
A dictionary can contain other dictionaries as values. This is common in API responses (JSON format).
employees = {
"emp1": {"name": "Sanya", "year": 2022},
"emp2": {"name": "Rohan", "year": 2024}
}
print(employees["emp1"]["name"]) # Output: Sanya
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION