# Dictionaries in Python — Keys, Values and Real Programs

Source: https://skills101.in/learn/python/python-dictionaries — Skills101 free tutorial (Python Programming). Updated 2026-11-09.

A **dictionary** (dict) stores **key → value** pairs. Instead of remembering "marks are at index 2", you write `student["marks"]`.

![Keys name, age and city pointing to the values Asha, 21 and Jaipur; looking up the key city gives Jaipur](https://skills101.in/learn-img/python/dict-keys.svg)

## 1. Create and read

```python
student = {"name": "Asha", "age": 21, "city": "Jaipur"}
print(student["name"])
print(student.get("cgpa"))           # None instead of an error
print(student.get("cgpa", "N/A"))    # with a default
print(len(student), "age" in student)
```

```text
Asha
None
N/A
3 True
```

> `student["cgpa"]` would raise a **KeyError** because the key doesn't exist. Use `.get()` when a key might be missing.

## 2. Add, change and delete

```python
student = {"name": "Asha", "age": 21}
student["age"] = 22              # change
student["skills"] = ["python"]   # add
student.update({"city": "Pune", "age": 23})
del student["city"]
removed = student.pop("skills")
print(student, removed)
```

```text
{'name': 'Asha', 'age': 23} ['python']
```

Keys must be **unique** and **immutable** (strings, numbers, tuples). Values can be anything.

## 3. Looping

```python
prices = {"pen": 10, "notebook": 45, "bag": 600}
for item, price in prices.items():
    print(f"{item}: ₹{price}")
print(list(prices.keys()))
print(sum(prices.values()))
```

```text
pen: ₹10
notebook: ₹45
bag: ₹600
['pen', 'notebook', 'bag']
655
```

## 4. Counting with a dictionary (very common)

```python
text = "the cat and the hat and the bat"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)
```

```text
{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}
```

`counts.get(word, 0) + 1` means "current count (or 0 if new) plus one".

### Sort a dictionary by value

```python
counts = {"the": 3, "cat": 1, "and": 2}
top = sorted(counts.items(), key=lambda kv: kv[1], reverse=True)
print(top)
```

```text
[('the', 3), ('and', 2), ('cat', 1)]
```

## 5. Dictionary comprehension

```python
squares = {n: n * n for n in range(1, 5)}
print(squares)
```

```text
{1: 1, 2: 4, 3: 9, 4: 16}
```

## 6. Nested dictionaries (like JSON)

```python
college = {
    "name": "Skills101 Institute",
    "students": [
        {"name": "Asha", "marks": {"maths": 92, "dsa": 88}},
        {"name": "Ravi", "marks": {"maths": 74, "dsa": 81}},
    ],
}
for s in college["students"]:
    print(s["name"], s["marks"]["dsa"])
```

```text
Asha 88
Ravi 81
```

This is exactly the shape of data you get from web APIs (JSON).

## Common mistakes

- Using `d[key]` for a key that may not exist → KeyError. Use `get`.
- Trying to use a list as a key (lists are mutable → TypeError).
- Changing a dictionary's size while looping over it.

## Quick recap

- `{key: value}`; read with `d[key]` or `d.get(key, default)`.
- Add/change with `d[key] = value`; delete with `del` or `pop`.
- Loop with `.items()`, `.keys()`, `.values()`.
- Count with `d.get(k, 0) + 1`; sort items with `key=`.


Practice quiz and free certificate: https://skills101.in/learn/python/python-dictionaries