Python Introduction to Dictionaries
Table of Contents
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 value25 - 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
Alexprint(person["age"])Output
25If 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"] = 26print(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
Trueprint("country" in person)Output
FalseThis 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
nameagecityTo get the values, we use the key.
for key in person: print(person[key])Output
Alex25LondonWe can also loop through keys and values together using .items().
for key, value in person.items(): print(f"{key}: {value}")Output
name: Alexage: 25city: LondonThat 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: AlexAge: 20Courses: Math, Physics, ChemistryGPA: 3.8That 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.