Python Introduction to Dictionaries

In the last lesson, we learned about Python Set Methods. Now let’s store related values using clear keys instead of positions.

🧩 Let’s Talk About a Different Kind of Collection

We know about lists. We know about tuples. We know about sets.

Now let’s talk about dictionaries.

A dictionary is a collection of key-value pairs. We give each value a name. And we use that name to find the value.

Think of it like a real dictionary. We look up a word. And we find its meaning. The word is the key. The meaning is the value.

Or think of a phone book. We look up a person’s name. And we find their phone number. Name is the key. Phone number is the value.

That is exactly how Python dictionaries work.

πŸ”§ How to Create a Dictionary in Python

We create a dictionary by putting key-value pairs inside curly braces { }. Each pair is separated by a colon :. And pairs are separated by commas.

person = {
"name": "Alex",
"age": 25,
"city": "London"
}

That is a dictionary. It has three key-value pairs.

  • Key "name" has value "Alex"
  • Key "age" has value 25
  • Key "city" has value "London"

We can also create an empty dictionary.

empty = {}

That is an empty dictionary. Not an empty set. Let’s remember, {} creates a dictionary. set() creates an empty set.

βš™οΈ Accessing Values in a Python Dictionary

We access a value using its key. We put the key inside square brackets.

person = {
"name": "Alex",
"age": 25,
"city": "London"
}
print(person["name"])

Output

Alex
print(person["age"])

Output

25

If the key does not exist, we get a KeyError.

print(person["country"]) # Error!

Output

KeyError: 'country'

So let’s only use keys that exist. Or use the get() method, which we will see later.

πŸ§ͺ Adding and Changing Values in a Python Dictionary

Dictionaries are mutable. So we can add new key-value pairs. And we can change existing values.

To add a new pair:

person = {"name": "Alex", "age": 25}
person["city"] = "London"
print(person)

Output

{'name': 'Alex', 'age': 25, 'city': 'London'}

To change an existing value:

person["age"] = 26
print(person)

Output

{'name': 'Alex', 'age': 26, 'city': 'London'}

That is simple. We use the key to assign a new value.

πŸ“Œ Removing Items from a Python Dictionary

We can remove a key-value pair using del or pop().

Using del:

person = {"name": "Alex", "age": 25, "city": "London"}
del person["age"]
print(person)

Output

{'name': 'Alex', 'city': 'London'}

Using pop():

person = {"name": "Alex", "age": 25, "city": "London"}
age = person.pop("age")
print(age)
print(person)

Output

25
{'name': 'Alex', 'city': 'London'}

pop() also returns the value that was removed. del does not.

πŸ“– Checking If a Key Exists in Python

We use in.

person = {"name": "Alex", "age": 25}
print("name" in person)

Output

True
print("country" in person)

Output

False

This checks keys, not values. So "Alex" in person would be False, because β€œAlex” is a value, not a key.

πŸ” Looping Through a Python Dictionary

We can loop through a dictionary. By default, we loop through the keys.

person = {"name": "Alex", "age": 25, "city": "London"}
for key in person:
print(key)

Output

name
age
city

To get the values, we use the key.

for key in person:
print(person[key])

Output

Alex
25
London

We can also loop through keys and values together using .items().

for key, value in person.items():
print(f"{key}: {value}")

Output

name: Alex
age: 25
city: London

That is the most common way to loop through a dictionary.

🧭 Length of a Python Dictionary

We use len() to get the number of key-value pairs.

person = {"name": "Alex", "age": 25, "city": "London"}
print(len(person))

Output

3

⚠️ Keys Must Be Unique in Python Dictionaries

A dictionary cannot have two identical keys. If we try to add a duplicate key, it will overwrite the old value.

person = {"name": "Alex", "age": 25}
person["name"] = "Sam"
print(person)

Output

{'name': 'Sam', 'age': 25}

The old value β€œAlex” is gone. Because the key β€œname” already existed. So it was updated.

🎯 Keys Must Be Immutable in Python

Dictionary keys must be immutable. We can use strings, numbers, or tuples as keys. But we cannot use lists or other dictionaries.

valid = {"name": "Alex", 1: "one", (1, 2): "point"}

That is valid. String, integer, and tuple keys.

invalid = {[1, 2]: "point"} # Error!

Output

TypeError: unhashable type: 'list'

Lists cannot be keys. Because they are mutable.

πŸ“š Python Dictionaries: A Real-Life Example

Let’s store information about a student.

student = {
"name": "Alex",
"age": 20,
"courses": ["Math", "Physics", "Chemistry"],
"gpa": 3.8
}
print(f"Name: {student['name']}")
print(f"Age: {student['age']}")
print(f"Courses: {', '.join(student['courses'])}")
print(f"GPA: {student['gpa']}")

Output

Name: Alex
Age: 20
Courses: Math, Physics, Chemistry
GPA: 3.8

That is a clean way to store related information.

βœ… Another Example β€” Counting Words

sentence = "the quick brown fox jumps over the lazy dog the fox"
words = sentence.split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print(word_count)

Output

{'the': 3, 'quick': 1, 'brown': 1, 'fox': 2, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}

That is a classic use of dictionaries. Counting things.

πŸ—οΈ Common Mistakes with Python Dictionaries

❌ Mistake 1: Using a List as a Key

d = {[1, 2]: "value"} # Error!

So what do we do? We use a tuple.

d = {(1, 2): "value"}

🚫 Mistake 2: Accessing a Non-Existent Key

person = {"name": "Alex"}
print(person["age"]) # Error!

So what do we do? We use get() or check first.

print(person.get("age", "Not found"))

πŸ›‘ Mistake 3: Thinking Dictionaries Are Ordered

In Python 3.7 and later, dictionaries remember insertion order. But in older versions, they did not. Let’s not rely on order for older code. But for modern Python, order is preserved.

🐞 Mistake 4: Using {} for an Empty Set

empty = {}
print(type(empty)) # <class 'dict'>

So what do we do? We use set() for an empty set.

empty = set()

Next, we will learn about Python Dictionary Operations and work with keys and values in common ways.