Python18 min read

Python Dictionaries

Learn dictionaries deeply: key-value pairs, safe lookups, updates, looping, and common real-world patterns.

Emily Davis
September 8, 2025
5.2k223

A dictionary stores data as key-value pairs. You use dictionaries when you want to look up something by a meaningful key instead of a position.

Think of it like a real dictionary:
- you search a word (key)
- you get a meaning (value)

In programming:
- key: "name"
- value: "Rachel"

## Why dictionaries are important

Dictionaries appear everywhere:
- JSON responses from APIs
- user profiles (name, email, city)
- settings/config (theme, language, timeout)
- counting and grouping (how many times each word appears)

## Create a dictionary

```python
person = {
    "name": "Rachel",
    "age": 28,
    "city": "Houston"
}

print(person)
```

Expected output:

```
{'name': 'Rachel', 'age': 28, 'city': 'Houston'}
```

## Access values (strict vs safe)

### Strict access using brackets
```python
print(person["name"])
```

Expected output:

```
Rachel
```

If the key is missing, Python throws a `KeyError`.

### Safe access using get()
```python
print(person.get("age"))
print(person.get("email", "Not found"))
```

Expected output:

```
28
Not found
```

Use `get()` when the key might not exist.

## Add, update, and remove keys

```python
person = {"name": "Mark", "age": 25}

person["city"] = "Dallas"   # add
person["age"] = 26          # update

del person["age"]           # remove

print(person)
```

Expected output:

```
{'name': 'Mark', 'city': 'Dallas'}
```

## Loop through dictionaries

Keys:

```python
person = {"name": "Lisa", "age": 30, "city": "Phoenix"}

for key in person:
    print(key)
```

Expected output:

```
name
age
city
```

Values:

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

Expected output:

```
Lisa
30
Phoenix
```

Keys + values:

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

Expected output:

```
name: Lisa
age: 30
city: Phoenix
```

## Real pattern: counting items with a dictionary

This is a common interview and real-work pattern.

```python
words = ["apple", "banana", "apple", "orange", "banana", "apple"]
counts = {}

for w in words:
    counts[w] = counts.get(w, 0) + 1

print(counts)
```

Expected output:

```
{'apple': 3, 'banana': 2, 'orange': 1}
```

## Graph: dictionary lookup

```mermaid
flowchart LR
  A["key: 'name'"] --> B[(dict)]
  B --> C["value: 'Rachel'"]
  D["key: 'email'"] --> B --> E["default: 'Not found'"]
```

In the next lesson, you will learn tuples, a “fixed” sequence type used for data that should not change.
#Python#Beginner#Dictionaries