Dictionaries in Python | Python Course | Dataplexa

Dictionaries in Python

A dictionary stores data as key-value pairs. Instead of using a number to find an item like in a list, you use a meaningful label — the key — to retrieve its value instantly. Think of it like a contact book: you search by a person's name (the key) and get their phone number (the value).

Dictionaries are used in almost every real Python program — storing user profiles, representing products, handling JSON from APIs, counting word frequency, and managing application settings. Mastering dictionaries is one of the most valuable skills in Python.

Creating a Dictionary

Dictionaries are created using curly braces {}. Each item is written as key: value and pairs are separated by commas. Keys are usually strings, but values can be anything.

student = {
    "name"  : "Riya",
    "age"   : 20,
    "course": "Computer Science",
    "grade" : "A"
}

print(student)
{'name': 'Riya', 'age': 20, 'course': 'Computer Science', 'grade': 'A'}
  • Curly braces {} define a dictionary.
  • Each entry has a key (left of the colon) and a value (right of the colon).
  • Values can be any type — strings, numbers, booleans, lists, even other dictionaries.

Accessing Values

To get a value, write the dictionary name followed by the key in square brackets. For safer access, use the .get() method — it returns a default instead of crashing if the key does not exist.

student = {"name": "Riya", "age": 20, "course": "Computer Science"}

# Square bracket access — crashes if key missing
print(student["name"])
print(student["age"])

# .get() — safe access with optional default
print(student.get("course"))           # Returns the value
print(student.get("phone"))            # Key missing → returns None
print(student.get("phone", "N/A"))     # Key missing → returns "N/A"
Riya 20 Computer Science None N/A
  • Square brackets raise a KeyError if the key does not exist. Use them when you are certain the key is there.
  • .get(key, default) is the professional choice — no crashes, clean fallback values.

Adding and Updating Items

Dictionaries are mutable. Assigning a value to a new key adds it. Assigning to an existing key overwrites the old value. Both use the same syntax.

product = {"title": "Wireless Headphones", "price": 2999}
print("Before:", product)

# Adding new keys
product["brand"]    = "SoundMax"
product["in_stock"] = True

# Updating an existing key
product["price"] = 2499

print("After:", product)
Before: {'title': 'Wireless Headphones', 'price': 2999} After: {'title': 'Wireless Headphones', 'price': 2499, 'brand': 'SoundMax', 'in_stock': True}

Removing Items

Python provides several ways to remove items — each suited to a slightly different situation.

settings = {"theme": "dark", "language": "English", "font_size": 14, "auto_save": True, "debug_mode": False}

# del — removes a key permanently, no return value
del settings["debug_mode"]
print("After del:", settings)

# pop() — removes a key and returns its value
removed_font = settings.pop("font_size")
print("Removed value:", removed_font)
print("After pop:", settings)

# popitem() — removes the last inserted key-value pair
last = settings.popitem()
print("Last item removed:", last)

# clear() — removes everything, leaves an empty dict
settings.clear()
print("After clear:", settings)
After del: {'theme': 'dark', 'language': 'English', 'font_size': 14, 'auto_save': True} Removed value: 14 After pop: {'theme': 'dark', 'language': 'English', 'auto_save': True} Last item removed: ('auto_save', True) After clear: {}
  • Use del when you just want the key gone.
  • Use pop() when you need the value after removing it.
  • popitem() removes the last inserted pair as a tuple.
  • clear() empties the dictionary — the variable still exists, it just becomes {}.

Essential Dictionary Methods

The three most important methods are .keys(), .values(), and .items(). You will use these constantly in real programs.

capitals = {"India": "New Delhi", "Japan": "Tokyo", "France": "Paris", "Brazil": "Brasília"}

print("Keys  :", capitals.keys())
print("Values:", capitals.values())
print("Items :", capitals.items())

# Convert to a plain list
key_list = list(capitals.keys())
print("Keys as list:", key_list)
Keys : dict_keys(['India', 'Japan', 'France', 'Brazil']) Values: dict_values(['New Delhi', 'Tokyo', 'Paris', 'Brasília']) Items : dict_items([('India', 'New Delhi'), ('Japan', 'Tokyo'), ('France', 'Paris'), ('Brazil', 'Brasília')]) Keys as list: ['India', 'Japan', 'France', 'Brazil']

Looping Through a Dictionary

Use a for loop to go through every item. The .items() pattern is the most useful — it gives you both the key and value at the same time.

employee = {"name": "Arjun", "department": "Engineering", "salary": 95000, "remote": True}

# Keys only
for key in employee:
    print(key)

# Values only
for value in employee.values():
    print(value)

# Key and value together (most common)
for key, value in employee.items():
    print(f"  {key}: {value}")
name department salary remote Arjun Engineering 95000 True name: Arjun department: Engineering salary: 95000 remote: True

Checking if a Key Exists

Use in and not in to check whether a key exists before accessing it. This prevents KeyError crashes.

user = {"username": "dev_learner", "email": "learner@example.com", "age": 24}

if "email" in user:
    print("Email found:", user["email"])

if "phone" not in user:
    print("Phone not stored in this profile.")

# Set a default if key is missing
if "country" not in user:
    user["country"] = "India"
    print("Country set to default:", user["country"])
Email found: learner@example.com Phone not stored in this profile. Country set to default: India

Nested Dictionaries

A dictionary can contain other dictionaries as values. This is how real JSON data from APIs is structured — and how you store multiple related records in one clean structure.

students = {
    "S001": {"name": "Priya", "marks": 88, "grade": "B+"},
    "S002": {"name": "Kiran", "marks": 95, "grade": "A"}
}

# Access an entire inner record
print("S001 record:", students["S001"])

# Access a specific field — outer key then inner key
print("S002 Name :", students["S002"]["name"])
print("S002 Marks:", students["S002"]["marks"])

# Loop through all students
for student_id, details in students.items():
    print(f"  {student_id} | {details['name']} | {details['grade']}")
S001 record: {'name': 'Priya', 'marks': 88, 'grade': 'B+'} S002 Name : Kiran S002 Marks: 95 S001 | Priya | B+ S002 | Kiran | A

Dictionary Comprehension

Dictionary comprehension builds a dictionary in a single line using a loop — the same idea as list comprehension but produces a dictionary instead.

# Regular way (longer)
squares_normal = {}
for n in range(1, 6):
    squares_normal[n] = n * n
print("Normal:", squares_normal)

# Comprehension way — same result in one line
squares_comp = {n: n * n for n in range(1, 6)}
print("Comprehension:", squares_comp)

# With a condition — only even numbers
even_squares = {n: n * n for n in range(1, 11) if n % 2 == 0}
print("Even squares:", even_squares)
Normal: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} Comprehension: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} Even squares: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

Merging Dictionaries with update()

The .update() method merges one dictionary into another. Existing keys are overwritten; new keys are added.

base_profile = {"username": "coder_99", "email": "coder@example.com", "plan": "free"}

updates = {"plan": "premium", "country": "India", "verified": True}

base_profile.update(updates)

for key, value in base_profile.items():
    print(f"  {key}: {value}")
username: coder_99 email: coder@example.com plan: premium country: India verified: True

Copying a Dictionary

Using = does NOT create a separate copy — both variables point to the same dictionary. Use .copy() for an independent duplicate.

original = {"item": "Laptop", "price": 80000}

# Wrong — both point to the same dictionary
wrong_copy = original
wrong_copy["price"] = 999
print("Original after wrong copy change:", original)

# Reset
original = {"item": "Laptop", "price": 80000}

# Correct — independent copy
correct_copy = original.copy()
correct_copy["price"] = 999
print("Original stays safe:", original)
print("Copy changed:", correct_copy)
Original after wrong copy change: {'item': 'Laptop', 'price': 999} Original stays safe: {'item': 'Laptop', 'price': 80000} Copy changed: {'item': 'Laptop', 'price': 999}

Real World Example — Word Frequency Counter

One of the most classic uses of a dictionary — counting how many times each word appears in a piece of text. This logic is used in search engines, spam filters, and text analysis tools.

sentence = "python is great python is easy python is fun to learn"
words = sentence.split()

word_count = {}
for word in words:
    if word in word_count:
        word_count[word] += 1
    else:
        word_count[word] = 1

for word, count in word_count.items():
    print(f"  '{word}' → {count} time(s)")
'python' → 3 time(s) 'is' → 3 time(s) 'great' → 1 time(s) 'easy' → 1 time(s) 'fun' → 1 time(s) 'to' → 1 time(s) 'learn' → 1 time(s)

Quick Reference Table

ConceptSyntaxWhat It Does
Created = {"key": "value"}Stores key-value pairs
Accessd["key"]Returns value; KeyError if missing
Safe accessd.get("key", default)Returns default if key missing
Add / Updated["key"] = valueAdds if new; overwrites if exists
Deletedel d["key"]Removes key permanently
Remove + get valued.pop("key")Removes and returns value
All keysd.keys()View of all keys
All valuesd.values()View of all values
All pairsd.items()Key-value pairs as tuples
Key exists"key" in dReturns True or False
Merged1.update(d2)Adds d2 into d1
Copyd2 = d1.copy()Independent duplicate
Nested accessd["key"]["inner"]Dictionary inside a dictionary

Practice

A dictionary stores data as __________ pairs.



Which method safely accesses a dictionary value and returns a default if the key is missing?



Which method removes a key from a dictionary AND returns its value?



Which method returns all key-value pairs as tuples?



To create an independent duplicate of a dictionary, use the __________ method.



Quick Quiz

What error is raised when you access a missing key using square brackets?





What does a dictionary look like after calling .clear()?





Given d = {"name": "Alex", "age": 25}, what does "age" in d return?





Which method merges all key-value pairs from one dictionary into another?





How many key-value pairs does d = {"a": 1, "b": 2, "c": 3} have?





NEXT UP
Sets in Python
Learn about sets — collections that automatically remove duplicates and make comparing groups of data incredibly easy using union, intersection, and difference operations.