Course topics

By WebNest Studio Engineering Team

Python Tutorial

Python Dictionaries and Dictionary Methods

A dictionary maps keys to values: a student id to a name, a product code to a price, a word to its count. Lookups by key are fast (O(1) on average), dictionaries keep insertion order (since Python 3.7), and JSON data from APIs maps directly onto them.

This lesson covers creating dictionaries, reading and updating values safely, every dictionary method — get, keys, values, items, update, pop, popitem, setdefault, fromkeys, clear, copy — merging, dict comprehensions and nested dictionaries.

Why it matters

The dictionary is the most important data structure in Python. JSON from an API becomes dictionaries, a database row is naturally a dictionary, and keyword arguments and even objects' attributes are stored in them. Counting, grouping and looking things up by key are all dictionary tasks, and doing them fluently is a core skill.

Creating and Accessing

Create with braces {"name": "Asha", "age": 24}, dict(name="Asha"), dict(zip(keys, values)) or a comprehension. Keys must be hashable and unique; values can be anything. d[key] raises KeyError for missing keys, while d.get(key, default) returns a default. Assigning d[key] = value adds or updates.

The Methods

Every dict method:

  • get(k, default) — safe read.
  • keys(), values(), items() — live views for iteration.
  • update(other) — merge in another dict or key/value pairs; d1 | d2 and d1 |= d2 also merge (3.9+).
  • pop(k, default) — remove and return a value; popitem() removes the last inserted pair.
  • setdefault(k, default) — return the value, inserting the default if the key is missing.
  • fromkeys(keys, value) — class method creating a dict with the same value for each key.
  • clear() — remove everything; copy() — shallow copy.

Iterating and Transforming

Iterating a dict yields keys; use .items() for key/value pairs. Dict comprehensions build or filter dictionaries in one expression. Sort by value with sorted(d.items(), key=lambda kv: kv[1]). Do not add or remove keys while iterating over a dict.

Nested Dictionaries

Real data is often nested — an API response with a user containing an address containing a city. Access with chained keys (data["user"]["address"]["city"]) or safely with chained get calls. For counting and grouping, collections.Counter and defaultdict (see the collections lesson) are even more convenient.

Examples

Creating, reading, adding and updating

Python
student = {"name": "Asha", "age": 24, "courses": ["Python"]}
print(student["name"], student.get("city"), student.get("city", "Unknown"))
student["city"] = "Pune"
student["age"] += 1
student["courses"].append("SQL")
print(student)
print(dict(zip(["a", "b"], [1, 2])), dict(x=1, y=2))
try:
    student["email"]
except KeyError as e:
    print("KeyError:", e)
Output
Asha None Unknown
{'name': 'Asha', 'age': 25, 'courses': ['Python', 'SQL'], 'city': 'Pune'}
{'a': 1, 'b': 2} {'x': 1, 'y': 2}
KeyError: 'email'

Every dictionary method

Python
prices = {"pen": 10, "book": 250}
print(list(prices.keys()), list(prices.values()), list(prices.items()))

prices.update({"bag": 899, "pen": 12})
print("update    :", prices)
removed = prices.pop("book")
print("pop       :", removed, prices, prices.pop("lamp", "not found"))
print("popitem   :", prices.popitem(), prices)
print("setdefault:", prices.setdefault("ink", 40), prices.setdefault("pen", 99), prices)
print("fromkeys  :", dict.fromkeys(["a", "b", "c"], 0))
copy_ = prices.copy()
prices.clear()
print("clear     :", prices, "copy:", copy_)
print("merge     :", {"a": 1, "b": 2} | {"b": 3, "c": 4})
Output
['pen', 'book'] [10, 250] [('pen', 10), ('book', 250)]
update    : {'pen': 12, 'book': 250, 'bag': 899}
pop       : 250 {'pen': 12, 'bag': 899} not found
popitem   : ('bag', 899) {'pen': 12}
setdefault: 40 12 {'pen': 12, 'ink': 40}
fromkeys  : {'a': 0, 'b': 0, 'c': 0}
clear     : {} copy: {'pen': 12, 'ink': 40}
merge     : {'a': 1, 'b': 3, 'c': 4}

Iterating, sorting by value, comprehensions and grouping

Python
scores = {"Asha": 91, "Ravi": 72, "Meera": 88, "Kiran": 65}
for name, score in scores.items():
    print(f"{name}: {score}")

top = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)[:2]
print("Top 2:", top)

passed = {n: s for n, s in scores.items() if s >= 70}
print(passed)

words = ["apple", "avocado", "banana", "blueberry", "cherry"]
groups = {}
for w in words:
    groups.setdefault(w[0], []).append(w)
print(groups)
Output
Asha: 91
Ravi: 72
Meera: 88
Kiran: 65
Top 2: [('Asha', 91), ('Meera', 88)]
{'Asha': 91, 'Ravi': 72, 'Meera': 88}
{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}

Nested dictionaries (like JSON from an API)

Python
response = {
    "user": {"id": 7, "name": "Asha", "address": {"city": "Pune", "pin": "411001"}},
    "orders": [{"id": 101, "total": 2999}, {"id": 102, "total": 499}],
}
print(response["user"]["address"]["city"])
print(response.get("user", {}).get("phone", {}).get("mobile", "no phone"))
print(sum(o["total"] for o in response["orders"]))
Output
Pune
no phone
3498

Common Mistakes

  • Using d[key] for keys that might be missing instead of d.get(key).
  • Using mutable objects (lists) as keys.
  • Changing a dict's size while iterating over it (RuntimeError).
  • Using dict.fromkeys(keys, []) — every key shares the same list.
  • Assuming copy() deep-copies nested values.

Exercise

Group the words by their first letter, so that each letter maps to the list of words that start with it. Print the resulting dictionary.

Expected output: {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}

Python · starter code
words = ["apple", "avocado", "banana", "blueberry", "cherry"]

groups = {}

# TODO: add each word to the list stored under its first letter

print(groups)
Show hints
  • The first time a letter is seen, there is no list for it yet.
  • groups.setdefault(letter, []) returns the existing list, or stores and returns a new empty one.
Show solution
Python · solution
words = ["apple", "avocado", "banana", "blueberry", "cherry"]

groups = {}

for word in words:
    groups.setdefault(word[0], []).append(word)

print(groups)

Quick quiz

1. What happens when d["missing"] is read and the key is not in the dictionary?

  • A. KeyError is raised
  • B. It returns None
  • C. It returns an empty string
  • D. The key is added
Show answer

A. Use d.get("missing") to get None, or a default, instead of an error.

2. Which of these can be used as a dictionary key?

  • A. [1, 2]
  • B. (1, 2)
  • C. {"a": 1}
  • D. {1, 2}
Show answer

B. Keys must be hashable. A tuple of hashable values is; lists, dicts and sets are not.

3. In what order does a dictionary return its keys when it is iterated?

  • A. Sorted order
  • B. Random order
  • C. The order in which the keys were inserted
  • D. Reverse order
Show answer

C. Insertion order has been guaranteed since Python 3.7.

Interview questions

What is the difference between d[key] and d.get(key)?

Show answer

d[key] raises KeyError when the key is absent. d.get(key) returns None in that case, or a default given as the second argument, as in d.get(key, 0). Use the square brackets when a missing key is a bug that should be noticed, and get when a missing key is expected.

How do you loop over the keys and values of a dictionary?

Show answer

Looping over the dictionary itself gives the keys. d.values() gives the values, and d.items() gives key-value pairs that can be unpacked: for key, value in d.items():. To loop in sorted order, wrap the call in sorted(). Keys must not be added or removed while looping over the dictionary.

How does a dictionary find a key so quickly?

Show answer

It is a hash table. The key's hash value is computed and used to go straight to the slot where the entry is stored, without examining the other entries, so a lookup takes about the same time for ten keys as for ten million. This is why keys must be hashable and must not change while they are in the dictionary.

Key Points to Remember

  • Dicts map unique hashable keys to values and keep insertion order.
  • get() reads safely; assignment adds or updates.
  • keys/values/items views, update or |, pop/popitem, setdefault, fromkeys, clear, copy.
  • Dict comprehensions build and filter dictionaries concisely.
  • Nested dicts mirror JSON; chain get() for safe access.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering