๐Ÿ“˜ CodingMarble Learn

Dictionaries in Python: Key-Value Pairs and Methods

A dictionary is a mutable collection of key: value pairs in curly braces, like {"Ravi": 85}. Keys are unique and immutable; values can be anything. We add or change a pair with d[key] = value, read with d[key] or d.get(key), traverse with for k in d, and use methods such as keys(), values(), items(), update(), pop(), popitem() and clear().

๐ŸŽฌ Step-by-step story

  1. A dictionary stores key: value pairs, like names on lockers. Keys are unique.
  2. Start with {} and add pairs with d[key] = value.
  3. Read a value by its key; get() avoids an error for a missing key.
  4. Traverse the keys, values or pairs with a for loop.
  5. An old key changes its value; del, pop and clear remove pairs.
  6. Your turn: type a word and build a letter-count dictionary.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

๐Ÿค” Common doubts, cleared

Why can't a list be a key?

Keys must never change, so Python can find them quickly. A list is mutable, so it is not allowed. A tuple is fine.

What happens if I add a key that already exists?

No new locker is made. The value inside the existing locker is replaced.

When should I use get() instead of d[key]?

When the key may be missing. get() returns None or your default instead of stopping the program with KeyError.

Does a dictionary have an order?

Since Python 3.7 it remembers insertion order, so loops go in the order you added pairs. But you still access by key, not by index.

How do I start an empty dictionary?

d = {} or d = dict(). Note that {} is a dictionary, not a set.

What is a dictionary? Key-value pairs

A dictionary (dict) stores data as key: value pairs in { }.

marks = {"Ravi": 85, "Asha": 92}

Creating a dictionary

d = {}                          # empty
d = dict()                      # empty
d = {"roll": 5, "name": "Ira"}
d = dict(roll=5, name="Ira")
d = dict([("roll", 5), ("name", "Ira")])

d = {}
for i in range(3):              # from input
    n = input("Name: ")
    d[n] = int(input("Marks: "))

Accessing and traversing

d[key] gives the value; a missing key gives KeyError. d.get(key, default) returns the default (or None) instead of an error.

key in d checks if a key exists (it checks keys, not values).

for k in d:                  # keys
    print(k, d[k])
for k, v in d.items():       # pairs
    print(k, v)

Updating and deleting

Dictionary methods and functions

Try it: count the letters

Type this program and run it with your own name:

word = input("Word: ")
d = {}
for ch in word:
    d[ch] = d.get(ch, 0) + 1
print(d)

Predict the output for "banana" first. Then open step 6 of the 3D, type the same word, and watch each locker fill.

Key formulas and definitions

Worked examples

1. d = {"a": 1, "b": 2}. What is d after d["c"] = 3 and d["a"] = 10?

"c" is new โ†’ added. "a" exists โ†’ changed. d = {"a": 10, "b": 2, "c": 3}.

2. d = {"pen": 10, "book": 50}. What do d.get("bag") and d.get("bag", 0) return?

None and 0. Neither raises an error, unlike d["bag"], which gives KeyError.

3. Find the total of the values in {"Mon": 30, "Tue": 45, "Wed": 25}.

sum(d.values()) = 30 + 45 + 25 = 100.

4. Write a program to print the name of the topper from marks = {"Ravi": 85, "Asha": 92, "Mohan": 78}.

top = "" best = -1 for k, v in marks.items(): if v > best: best, top = v, k print(top) โ†’ Asha

5. Count each character in "banana".

Using d[ch] = d.get(ch, 0) + 1 for each letter: {"b": 1, "a": 3, "n": 2}.

6. d = {1: "x", 2: "y", 3: "z"}. What is d after d.pop(2) and d.popitem()?

pop(2) removes 2: "y" โ†’ {1: "x", 3: "z"}. popitem() removes the last pair (3, "z") โ†’ {1: "x"}.

Common mistakes

Practice quiz

1. Which brackets create a dictionary?
2. d = {"a": 1}; d["a"] = 5. Now d is:
3. Which method returns all key-value pairs?
4. d["x"] for a missing key "x" gives:
5. Which can NOT be a key?

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What is a dictionary in Python?

A mutable collection of unique key: value pairs in curly braces, accessed by key.

What is the difference between pop() and popitem()?

pop(key) removes the pair with that key and returns its value; popitem() removes and returns the last added pair.

How do you traverse a dictionary?

for k in d: print(k, d[k]) or for k, v in d.items(): print(k, v).

Where this is taught

CBSE (India)Class 11Computational Thinking and Programming - 1
CBSE (India)Class 11Introduction to Python

Learn first

Learn next

Related lessons

All Informatics Practices lessons