Course 1.1Lesson 3 of 5
A for loop over a dictionary goes through the keys, and d.items() gives the key and the value in each round. To count with a dictionary, the key is the thing that you count and the value is how many times you have seen it, and counts[x] = counts.get(x, 0) + 1 does the work, because get gives 0 the first time. The same idea counts letters, words or any items. To find the key with the highest value, go through the items and remember the best so far.
Try the code and the simulations beside the lesson.
After this lesson you can
This is the most useful trick with dictionaries. The key is the thing that you count. The value is how many times you have seen it.
Predict first: how many times does each letter of banana appear? Then run it.
The line counts[letter] = counts.get(letter, 0) + 1 does the work. Read it from the right:
counts.get(letter, 0) gives the count so far, or 0 the first time we see the letter.1.Follow the picture: after the first b, the dictionary is {"b": 1}. After the first a, {"b": 1, "a": 1}. And so on. After six rounds: b is 1, a is 3, n is 2.
Without get, you would have to write an if: if the letter is not a key, set it to 1, else add 1. The get makes it one line.
counts.get(ch, 0) is the trick: it gives 0 for a letter that has not been counted yet, so the first count becomes 1.
The same idea counts words. The method split() cuts a sentence into a list of words, and the loop goes through that list.
Before you count words in a real text, think about clean-up. "The" and "the" are different keys. "dog." and "dog" are different keys. You will meet lower() and replace() for this in the lesson on working with text. For now, our sentence is already clean.
You can count anything: the letters of a word, the words of a sentence, the marks of a class, the grades, the cities of a list. The steps are always the same.
counts = {}.counts[item] = counts.get(item, 0) + 1.0 in get. counts.get(letter) + 1 gives a TypeError the first time, because None + 1 is not possible."The" and "the" are two words.for x in counts and expecting the pair. You get only the key. Use .items().Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
for key in d: goes through the keys. for key, value in d.items(): gives both.counts[x] = counts.get(x, 0) + 1.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
"banana" have?counts.get("z", 0) give if "z" has not been counted?for k, v in d.items() give in each round?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.