Sitemap

Dictionary in Python

6 min readMar 3, 2026

--

A Dictionary in Python is a powerful built-in data structure used to store data in key–value pairs. It is one of the most widely used structures in real-world Python applications like APIs, databases, JSON handling, caching, and configuration management.

Unlike lists that use numeric indexes, dictionaries allow you to access data using meaningful keys.

Press enter or click to view image in full size

What is a Dictionary?

A dictionary is:

  • A collection of key-value pairs
  • Mutable (can be modified)
  • Keys must be unique
  • Keys must be immutable
  • Based on Hash Table implementation

Example:

student = {
"name": "Sam",
"age": 25,
"course": "Python"
}

# Here:
# - "name" → Key
# - "Sam" → Value

Why Use Dictionary?

Imagine storing student details.

  • Using List:
student = ["Sam", 25, "Python"]

Problem: What does index 1 represent?

  • Using Dictionary:
student = {
"name": "Sam",
"age": 25,
"course": "Python"
}

Now data is meaningful and self-explanatory.

Key Features of Dictionary

Press enter or click to view image in full size

Creating Dictionary

1. Using Curly Braces

data = {"a": 1, "b": 2}

2. Using dict() Constructor

data = dict(a=1, b=2)

3. Empty Dictionary

data = {}

Accessing Elements

1. Using Key

print(data["a"])

2. Using get() (Safe Method)

print(data.get("a"))
print(data.get("z", "Not Found"))

Difference:

  • data[“z”] → KeyError
  • data.get(“z”) → Returns None

Updating Dictionary

data["c"] = 3
data["a"] = 100
data.update({"d": 4})

Removing Elements

1. pop() : When You Need the Value After Removing

  • Sometimes you don’t just want to delete a key — you also want to use the value before it disappears.
  • Example:
# Imagine a login system:
sessions = {
"user1": "active",
"user2": "inactive"
}

status = sessions.pop("user1")
print(f"User1 was {status}")

Here:

  • We remove “user1”
  • But we still need the status before deleting.

If we used del, we would lose the value.

When to Use:

  • When removing + processing value
  • When transferring data
  • When safely removing with default
value = data.pop("x", None)  # Safe removal

2. Use popitem() : When Treating Dictionary Like a Stack

Since Python 3.7+, dictionaries maintain insertion order.

popitem() removes the last inserted item (LIFO behavior).

That’s exactly how a stack works.

Stack = Last In, First Out (LIFO)

tasks = {}
tasks["task1"] = "Clean"
tasks["task2"] = "Study"
tasks["task3"] = "Workout"

print(tasks.popitem()) # ('task3', 'Workout')

Last added task gets removed first.

3. Use del : Simple Deletion

When you just want to remove something
and don’t care about its value.

del data["b"]

It’s clean and direct.

Get Saurabh Gandhi’s stories in your inbox

Join Medium for free to get updates from this writer.

When NOT to use pop():

  • If you don't need the value, del is slightly clearer in intent.

When to Use:

  • Simple cleanup
  • Removing known key
  • Cleaner syntax when return value not required

4. Use clear() : Reset Dictionary

When you want to empty everything
but keep the dictionary object alive.

data.clear()

Useful when:

  • Reusing the dictionary
  • Resetting state
  • Clearing cache

Important Difference:

data = {}

This creates a new dictionary object

But:

data.clear()

Clears the same dictionary object in memory.

Press enter or click to view image in full size

Looping Through Dictionary

for key in data:
print(key)

for value in data.values():
print(value)

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

Now let’s deeply understand what’s happening in each loop and why we use each form.

data = {"a": 10, "b": 20, "c": 30}

1. for key in data:

for key in data:
print(key)

# output:
# a
# b
# c

✅ What it does:

  • Iterates over keys only.

🧠 Why?

  • When you loop directly over a dictionary:
for x in data:
  • Python automatically iterates over keys.

Internally, it behaves like:

for key in data.keys():

🎯 When to Use:

  • When you only need keys
  • When checking if key exists
  • When modifying values using keys

👉 Example:

for key in data:
data[key] += 5

— — — — — — — — — — — — — — —

2. for value in data.values():

for value in data.values():
print(value)

# output:
# 10
# 20
# 30

✅ What it does:

  • Iterates over values only.

🧠 Why?

  • .values() returns a dictionary view object containing all values.
  • It does NOT create a new list (memory efficient).

🎯 When to Use:

  • When only values matter
  • When calculating sum / max / min

👉 Example:

total = sum(data.values())

— — — — — — — — — — — — — — — -

3. for key, value in data.items():

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

# output:
# a 10
# b 20
# c 30

✅ What it does:

  • Iterates over both key and value together.

🧠 Why?

  • .items() returns:
("a", 10)
("b", 20)
("c", 30)
  • Each item is a tuple → (key, value)

Python automatically unpacks it:

for (key, value) in data.items():

🎯 When to Use:

  • When you need both key and value
  • Most common in real projects
  • Clean and readable

data.items() is slightly more efficient than:

❌ This

for key in data:
print(key, data[key])
  • Because .items() avoids extra lookup.

— — — — — — — —

📊 Quick Comparison

Press enter or click to view image in full size

Dictionary Comprehension

Dictionary comprehension is a short and powerful way to create a dictionary using a single line of code.

It is similar to list comprehension, but it creates a dictionary.

Syntax

{key_expression: value_expression for item in iterable}

Examples

# Example 1: Create Dictionary from Range
squares = {i:i*i for i in range(1,6)}
print(squares)

# output
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Here:
# - x → key
# - x*x → value
#=========================================================================


# Example 2: From List to Dictionary
numbers = [1,2,3,4]
result = {i:i*2 for i in numbers}
# output
# {1: 2, 2: 4, 3: 6, 4: 8}
#=========================================================================


# Example 3: With Condition (Filtering)
even_squares = {i:i*i for i in range(1,11) if i % 2 == 0}
print(even_squares)
# output
# {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
#=========================================================================


# Example 4: From Two Lists (Using zip)
keys = ["a", "b", "c"]
values = [10, 20, 30]
data = {k:v for k,v in zip(keys,values)}
print(data)
# output
# {'a': 10, 'b': 20, 'c': 30}
#=========================================================================


# Example 5: With If-Else (Conditional Expression)
result = {i:("even" if i%2==0 else "odd") for i in range(1,6)}
print(result)
# output
# {1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd'}
#=========================================================================

🎯 When NOT to Use It

  • Logic is too complex
  • Code becomes unreadable
  • Multiple nested conditions
  • In such cases, use normal for loop.

Nested Dictionary

A nested dictionary is a dictionary inside another dictionary.

In simple words:
- Dictionary within Dictionary

Basic Structure

data = {
"key1": {
"subkey1": "value1",
"subkey2": "value2"
},
"key2": {
"subkey3": "value3"
}
}

Example:

students = {
"student1": {
"name": "Rahul",
"age": 20
},
"student2": {
"name": "Amit",
"age": 22
}
}

print(students)

Accessing Values

print(students["student1"]["name"])
  • First access outer key
  • Then access inner key

Adding Data to Nested Dictionary

company = {
"emp1": {
"name": "John",
"salary": 50000,
"department": "IT"
},
"emp2": {
"name": "Sara",
"salary": 60000,
"department": "HR"
}
}

company["emp3"] = {
"name": "David",
"salary": 70000,
"department": "Finance"
}
print(company["emp2"]["salary"])

Using get() Safely

print(company.get("emp1", {}).get("name"))
  • Prevents KeyError

Looping Through Nested Dictionary

for emp_id, details in company.items():
print("Employee ID:", emp_id)
for key, value in details.items():
print(key, ":", value)

# output:
# Employee ID: emp1
# name : John
# salary : 50000
# department : IT

When to Use Nested Dictionary?

  • Storing structured data
  • JSON-like data
  • API responses
  • Database records
  • Configuration settings

Example: JSON data from web APIs is usually nested.

Questions

  1. What is a dictionary in Python?
  2. How is a dictionary different from a list?
  3. Are dictionary keys ordered?
  4. Can dictionary keys be duplicated?
  5. What is the internal data structure of a dictionary?
  6. Is dictionary mutable or immutable?
  7. How do you access a value in a dictionary?
  8. What happens if you access a non-existing key?
  9. Difference between pop() and del?
  10. When do we use pop()?
  11. What does pop() return?
  12. What happens if key is not found in pop()?
  13. What is popitem()?
  14. How does popitem() behave in Python 3.7+?
  15. When would you use clear()?
  16. Difference between clear() and data = {}?

--

--

Saurabh Gandhi
Saurabh Gandhi