ይህ ትምህርት ገና ወደ አማርኛ አልተተረጎመም፤ ስለዚህ በእንግሊዝኛ ቀርቧል። የእንግሊዝኛውን ገጽ ክፈቱ
Dictionaries
Your phone doesn't find Hana's number by position ("the 14th contact"). It finds it by her name. In this lesson you'll build that kind of lookup with a dictionary, handle names that aren't there without crashing, and use a dictionary to count things, one of the most useful plans in programming.
The phone numbers in this lesson are made up.
Look it up by name
A (or dict) pairs each key with a value. You write it in curly brackets, with a colon between each key and its value:
contacts = {
"Abel": "0900 000 001",
"Hana": "0900 000 002",
"Selam": "0900 000 003",
}
print(contacts["Hana"])
print(len(contacts))In the editor, press Escape then Tab to move on.
contacts["Hana"] looks like indexing a list, but the thing in the brackets is a key,
not a position. Change it to look up Selam.
The same square brackets add a new pair, or change the value of a key that's already
there. del removes a pair:
contacts = {"Abel": "0900 000 001", "Hana": "0900 000 002", "Selam": "0900 000 003"}
contacts["Dawit"] = "0900 000 004"
contacts["Hana"] = "0900 000 222"
del contacts["Selam"]
print(contacts)In the editor, press Escape then Tab to move on.
A key can only appear once, so giving "Hana" a new number replaced the old one. Notice
the order: a dict keeps its pairs in the order they were added, and Dawit, added
last, comes last.
When the key isn't there
Looking up a key that isn't in the dict stops the program:
in asks about keys. Predict this:
ውጤቱን ገምቱ
Decide before you look. Guessing wrong is how this sticks.
cups = {"abol": 1, "tona": 2, "bereka": 3}
print("tona" in cups)
print(2 in cups)Python prints
True False
in checks the keys of a dict, never the values. "tona" is a key; 2 is only a value.
The other way is get(). It returns the value if the key is there, and None if it
isn't. Give it a second value and it returns that instead of None:
contacts = {"Abel": "0900 000 001", "Hana": "0900 000 002"}
print(contacts.get("Abel"))
print(contacts.get("Meron"))
print(contacts.get("Meron", "not saved"))In the editor, press Escape then Tab to move on.
ጥያቄ
d = {"a": 1}. What does d.get("x") return?
Going through a dict
A for loop over a dict goes through its keys. .values() gives the values, and
.items() gives each pair as a tuple, ready to unpack (lesson 4.3):
contacts = {"Abel": "0900 000 001", "Hana": "0900 000 002"}
for name in contacts:
print(name)
for number in contacts.values():
print(number)
for name, number in contacts.items():
print(f"{name}: {number}")In the editor, press Escape then Tab to move on.
.items() is the one you'll use most. Add a contact and run it again.
Counting with a dict: the tally plan
How many times does each word appear in a list? Keep a dict of counts: the word is the key, its count is the value. For each word, get the count so far (0 if the word is new) and add 1. This is the tally plan:
Step through it
Press Next to run one line at a time and watch each name change.Each row is one step: the line that just ran, and every name's value after it.
| Name | Value after line 1 |
|---|---|
| words | ['buna', 'shai', 'buna']new |
| countscounter | not made yet |
| wordlatest value | not made yet |
Output so far
Step 1 of 10
Step 1 of 10. Line 1: words = ["buna", "shai", "buna"]. words is now ['buna', 'shai', 'buna'].
| Step | Line | words | countscounter | wordlatest value | Printed |
|---|---|---|---|---|---|
| 1 | 1 | ['buna', 'shai', 'buna'] | not made yet | not made yet | |
| 2 | 2 | ['buna', 'shai', 'buna'] | {} | not made yet | |
| 3 | 3 | ['buna', 'shai', 'buna'] | {} | 'buna' | |
| 4 | 4 | ['buna', 'shai', 'buna'] | {'buna': 1} | 'buna' | |
| 5 | 3 | ['buna', 'shai', 'buna'] | {'buna': 1} | 'shai' | |
| 6 | 4 | ['buna', 'shai', 'buna'] | {'buna': 1, 'shai': 1} | 'shai' | |
| 7 | 3 | ['buna', 'shai', 'buna'] | {'buna': 1, 'shai': 1} | 'buna' | |
| 8 | 4 | ['buna', 'shai', 'buna'] | {'buna': 2, 'shai': 1} | 'buna' | |
| 9 | 3 | ['buna', 'shai', 'buna'] | {'buna': 2, 'shai': 1} | 'buna' | |
| 10 | 5 | ['buna', 'shai', 'buna'] | {'buna': 2, 'shai': 1} | 'buna' | {'buna': 2, 'shai': 1} |
counts is a whole group of counters, one per word. At step 4, "buna" isn't a key
yet, so get returns the default 0 and the count becomes 1. At step 8 it's already 1,
so it becomes 2. Without the default, counts["buna"] + 1 would be a KeyError the
first time. Add "buna" to the list once more and predict the new count before you run
it.
words = ["buna", "shai", "buna"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)In the editor, press Escape then Tab to move on.
መልመጃ
A small Amharic–English dictionary
Ask for an Amharic word and print its English meaning. If the word isn't in the
dictionary, print a friendly message instead of crashing. The Input box asks for
buna; try shai too.
Your code
words = {"selam": "hello", "buna": "coffee", "wuha": "water", "dabo": "bread"}
# Ask for a word, then print its meaning or a friendly messageIn the editor, press Escape then Tab to move on.
One answer per line, given to input() in order.
መፍትሄውን አሳይHide the solution
This is one way to solve it, not the only one. If yours prints the same thing, it works.
words = {"selam": "hello", "buna": "coffee", "wuha": "water", "dabo": "bread"}
word = input("Amharic word: ")
if word in words:
print(f"{word} means {words[word]}")
else:
print(f"Sorry, {word} isn't in this dictionary yet.")ዋና ዋና ነጥቦች
- A dict finds a value by its key:
contacts["Hana"]. Each key appears once. d[key] = valueadds or changes a pair;del d[key]removes one. Dicts keep the order pairs were added.- A missing key raises a
KeyError. Check within(it checks keys), or useget(key, default). - Loop over keys,
.values(), or.items()with unpacking. - The tally plan:
counts[word] = counts.get(word, 0) + 1.