What is a dictionary? Key-value pairs
A dictionary (dict) stores data as key: value pairs in { }.
marks = {"Ravi": 85, "Asha": 92}- Each key must be unique. It must be immutable: str, int, float or tuple (not a list).
- A value can be any type and can repeat.
- A dict is mutable: pairs can be added, changed and removed.
- Since Python 3.7, the pairs keep the order in which they were added, but we reach them by key, not by index.
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
d[key] = value: if the key exists, its value is changed; if not, a new pair is added.d.update(d2): adds or changes many pairs at once.del d[key]: deletes a pair (KeyError if missing).d.pop(key): deletes and returns the value.d.popitem(): deletes and returns the last added pair.d.clear(): empties the dictionary.
Dictionary methods and functions
len(d): number of pairsd.keys(),d.values(),d.items(): views of keys, values, pairsd.get(k, default)d.update(d2),d.pop(k),d.popitem(),d.clear()d.copy(): a separate copydict.fromkeys(keys, value): new dict with the given keys, all set to valued.setdefault(k, v): returns d[k]; if k is missing, adds it with vsorted(d): sorted list of keys;max(d),min(d)work on keys
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
- d = {key: value, โฆ}; keys unique and immutable
- d[k] = v โ add if new, change if old
- d.get(k, default) avoids KeyError
- keys(), values(), items(), update(), pop(), popitem(), clear(), copy(), fromkeys(), setdefault()
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
- Using d[0] to get the "first" item; a dict is reached by key, not index.
- Using a list as a key; keys must be immutable.
- Expecting "value in d" to search values; in checks keys only.
- Thinking a repeated key keeps both values; the later one replaces the earlier.