Dictionaries
Look things up by key, count and group with dictionaries, and loop over them.
18 min
A dictionary stores key: value pairs. You look a value up by its key instead of by position:
ages = {"Ada": 36, "Grace": 45}
print(ages["Ada"]) # 36
ages["Alan"] = 41 # add a new pair
ages["Ada"] = 37 # change an existing one
del ages["Grace"] # remove a pairKeys are usually strings or numbers and must be unique. Asking for a key that is not there raises a KeyError. Two safe ways to ask:
"Linus" in ages # False
ages.get("Linus") # None, no error
ages.get("Linus", 0) # 0, your own defaultfor name in ages: # keys
print(name)
for name, age in ages.items(): # key and value together
print(name, age)ages.keys(), ages.values() and ages.items() give the three views.
The most useful dictionary idiom is counting how often things appear:
counts = {}
for letter in "banana":
counts[letter] = counts.get(letter, 0) + 1
# {'b': 1, 'a': 3, 'n': 2}Read the loop body as "the new count is the old count, or 0 if I have not seen it, plus one".
Dictionary methods you will use
d[k]
- What it does
- value for key
k, orKeyError
d.get(k, default)
- What it does
- value, or
defaultif missing
k in d
- What it does
- True if the key exists
d.items()
- What it does
- all (key, value) pairs, for looping
d.pop(k)
- What it does
- remove the pair and return its value
len(d)
- What it does
- number of pairs
Choose the container by how you will look things up.
List
- Look up by
- position (index)
- Order matters
- yes
- Duplicates
- allowed
Best for a sequence: steps, scores over time
Dictionary
- Look up by
- key
- Order matters
- keeps insertion order, but you look up by key
- Duplicates
- keys must be unique
Best for a lookup: price by product, count by word
Write word_counts(text) that returns a dictionary counting how many times each word appears. Ignore capitals ("The the" counts as the twice) and split on whitespace.
Your code must satisfy
- word_counts("a b a")→{"a":2,"b":1}simple
- word_counts("The the THE")→{"the":3}case ignored
- word_counts("")→[]empty
- word_counts("to be or not to be")→{"to":2,"be":2,"or":1,"not":1}sentence
def word_counts(text):
passWrite invert(d) that swaps keys and values: invert({"a": 1, "b": 2}) is {"1": "a", "2": "b"}.
Because JSON keys are text, the tests make the new keys strings: convert each old value with str().
Your code must satisfy
- invert({"a": 1, "b": 2})→{"1":"a","2":"b"}two pairs
- invert({})→[]empty
- invert({"x": "red"})→{"red":"x"}words
def invert(d):
pass- A dictionary maps unique keys to values:
d[key],d[key] = value. - Use
.get(key, default)orinwhen the key may be missing. .items()loops over keys and values together.- Counting with
d[k] = d.get(k, 0) + 1is the idiom for frequencies.
Dictionary checks.
d = {"a": 1, "b": 2}. What is d["b"]?
- A1
- B2
- C"b"
- DKeyError
What does {"a": 1}.get("z", 0) return?
- ANone
- B0
- CKeyError
- D"z"
d = {"x": 5} then d["y"] = 7. What is len(d)?
Which is a good use of a dictionary?
- AThe scores of a game, in the order played
- BThe price of each product, looked up by name
- CThe letters of a word
- DA single number
To loop over keys and values together, write for k, v in d.():
Capitalisation, spacing and punctuation are ignored when grading.
Practise this lesson, not just read it
In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Python for Complete Beginners is planned around your week. Free.