Kahibaro
Discord Login Register

Dictionaries

Understanding Dictionaries

Dictionaries are a built‑in Python data type that store key–value pairs. They are useful when you want to look up a value using some kind of label (the key), instead of using a numeric index like in lists.

Some everyday examples of dictionaries in real life:

In Python, a dictionary:

Example:

student = {
    "name": "Alice",
    "age": 20,
    "is_student": True
}

Here "name", "age", and "is_student" are keys, and "Alice", 20, True are the values.

Creating Dictionaries

You can create dictionaries in several ways.

Using curly braces `{}`

The most common way:

person = {
    "first_name": "John",
    "last_name": "Doe",
    "age": 30
}

Keys are usually strings, but they can be many other types (with some rules; more on that later).

An empty dictionary:

empty_dict = {}

Using the `dict()` function

You can also create a dictionary with dict():

person = dict(first_name="John", last_name="Doe", age=30)

Notice:

Accessing Values

You get a value from a dictionary by using its key in square brackets:

person = {
    "first_name": "John",
    "last_name": "Doe",
    "age": 30
}
print(person["first_name"])  # John
print(person["age"])         # 30

If you use a key that does not exist, Python raises a KeyError:

print(person["height"])  # KeyError: 'height'

Using `get()` to avoid errors

The method get() lets you ask for a key safely:

print(person.get("age"))        # 30
print(person.get("height"))     # None (no error)
print(person.get("height", 0))  # 0 (default value)

get(key, default) returns:

Adding and Changing Entries

You add a new key–value pair or change an existing one using assignment:

Adding a new key–value pair

person = {"name": "Alice"}
person["age"] = 25  # add a new key 'age'
print(person)       # {'name': 'Alice', 'age': 25}

Changing an existing value

person["age"] = 26  # change existing value
print(person)       # {'name': 'Alice', 'age': 26}

Updating multiple keys with `update()`

The update() method lets you add or modify several keys at once:

person = {"name": "Bob", "age": 20}
person.update({"age": 21, "city": "London"})
print(person)
# {'name': 'Bob', 'age': 21, 'city': 'London'}

You can also use keyword arguments with update():

person.update(age=22, country="UK")

Removing Entries

Dictionaries provide several ways to remove items.

Using `del`

del deletes a specific key (and its value):

person = {"name": "Alice", "age": 26, "city": "Paris"}
del person["city"]
print(person)  # {'name': 'Alice', 'age': 26}

Using del with a missing key will cause a KeyError.

Using `pop()`

pop(key) removes the key and returns its value:

age = person.pop("age")
print(age)     # 26
print(person)  # {'name': 'Alice'}

You can provide a default value to avoid errors if the key is missing:

result = person.pop("height", None)
print(result)  # None (no error)

Using `popitem()`

popitem() removes and returns the last added key–value pair (in modern Python versions):

data = {"a": 1, "b": 2, "c": 3}
key, value = data.popitem()
print(key, value)  # 'c', 3 (typically)

This is mostly useful when you treat the dictionary like a stack of items.

Clearing all entries

To remove everything from a dictionary:

person.clear()
print(person)  # {}

Keys, Values, and Items

Dictionaries have helpful methods to look at their contents.

`keys()`

Returns a “view” of all keys:

person = {"name": "Alice", "age": 26, "city": "Paris"}
print(person.keys())  # dict_keys(['name', 'age', 'city'])

`values()`

Returns a view of all values:

print(person.values())  # dict_values(['Alice', 26, 'Paris'])

`items()`

Returns a view of all key–value pairs as tuples:

print(person.items())
# dict_items([('name', 'Alice'), ('age', 26), ('city', 'Paris')])

You can turn these views into lists if needed:

keys_list = list(person.keys())
values_list = list(person.values())
items_list = list(person.items())

Looping Over Dictionaries

Dictionaries are often used together with for loops.

Looping over keys (default)

When you loop directly over a dictionary, you get its keys:

person = {"name": "Alice", "age": 26, "city": "Paris"}
for key in person:
    print(key, "->", person[key])

This is the same as:

for key in person.keys():
    print(key, "->", person[key])

Looping over values

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

Looping over key–value pairs with `items()`

This is often the most convenient way:

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

This uses tuple unpacking: each item is a tuple (key, value), and for key, value in ... splits it into two variables.

Checking for Keys

To check if a key exists in a dictionary, use the in keyword:

person = {"name": "Alice", "age": 26}
print("name" in person)   # True
print("height" in person) # False

This checks keys, not values. To check for a value in values():

print(26 in person.values())  # True

Valid Keys (and Common Pitfall)

Not everything can be used as a dictionary key. Keys must be:

Using a list as a key will raise a TypeError:

bad_dict = {}
bad_dict[[1, 2, 3]] = "hello"  # TypeError: unhashable type: 'list'

Strings are a very common choice for keys in beginner programs.

Nested Dictionaries (Dictionaries Inside Dictionaries)

Dictionaries can contain other dictionaries as values. This is useful for representing structured data.

Example: students by ID

students = {
    "s001": {"name": "Alice", "age": 20},
    "s002": {"name": "Bob", "age": 22},
}
print(students["s001"]["name"])  # Alice

Here:

You can modify nested values by chaining square brackets:

students["s001"]["age"] = 21

Example: inventory of items

inventory = {
    "apple": {"price": 0.5, "quantity": 10},
    "banana": {"price": 0.3, "quantity": 5},
}
# Access banana price
print(inventory["banana"]["price"])  # 0.3
# Increase apple quantity
inventory["apple"]["quantity"] += 5

Common Dictionary Methods (Beginner‑Friendly)

Here are some useful methods again, summarized with simple examples:

user = {"name": "Alice", "age": 25}
# get()
print(user.get("age", 0))      # 25
print(user.get("height", 0))   # 0
# update()
user.update({"city": "Paris"})
user.update(age=26)
# pop()
age = user.pop("age", None)    # removes 'age' and returns 26
# keys(), values(), items()
print(list(user.keys()))
print(list(user.values()))
print(list(user.items()))

Typical Use Cases for Dictionaries

Dictionaries are particularly handy when:

Small Practice Ideas

Here are some simple tasks you can try (you don’t need to write full programs yet—just experiment in the Python shell or a script):

  1. Create a dictionary capitals that maps a few countries to their capital cities.
    • Look up the capital of one country.
    • Add a new country and its capital.
  2. Make a prices dictionary for 3 products.
    • Change the price of one product.
    • Loop over the dictionary and print: "Product: X, Price: Y".
  3. Create a contact dictionary with keys "name", "phone", "email".
    • Use get() to safely read a "address" key, providing a default like "Unknown".

These small experiments will help you feel comfortable with creating, reading, updating, and looping over dictionaries.

Views: 15

Comments

Please login to add a comment.

Don't have an account? Register now!