HOME HTML EDITOR C JAVA PHP python

Python Tutorial: Python Dictionaries

A dictionary in Python is a collection of key-value pairs written inside curly braces ({key: value}). Starting in Python 3.7+, dictionaries preserve insertion order, are mutable, and do not allow duplicate keys.

1. Creating & Accessing Dictionary Values

You access values using their key inside square brackets ([]) or safely using the get() method (which returns None or a default value instead of raising a KeyError if the key is missing):

student = {
    "name": "Rohan",
    "age": 21,
    "course": "Python"
}

print(student["name"])                # Rohan
print(student.get("age"))             # 21
print(student.get("grade", "N/A"))    # N/A (safe fallback)

2. Adding, Updating & Removing Items

Dictionaries are mutable — assigning to an existing key updates its value, while assigning to a new key adds a new pair:

user = {"username": "dev_amit", "active": True}

user["active"] = False          # Update existing key
user["role"] = "editor"         # Add new key-value pair
user.update({"city": "Pune"})   # Merge another dict

removed_role = user.pop("role") # Remove key and return value
print(user)
print("Removed:", removed_role)

3. Looping Through Dictionaries

You can iterate over keys, values, or both together using keys(), values(), and items():

prices = {"apple": 120, "banana": 60, "mango": 150}

for item, price in prices.items():
    print(f"{item}: Rs.{price}")

for k in prices.keys():
    print("Key:", k)

for v in prices.values():
    print("Value:", v)

4. Nested Dictionaries

A dictionary can contain other dictionaries inside it — very common when working with JSON data, user profiles, or configuration settings:

users = {
    "u1": {"name": "Neha", "plan": "Pro"},
    "u2": {"name": "Karan", "plan": "Free"}
}

print(users["u1"]["name"])  # Neha
print(users["u2"]["plan"])  # Free
Important: Dictionary keys must be immutable (such as strings, numbers, or tuples) and unique — if you repeat a key in a literal, the later value overwrites the earlier one.