Python Dictionary Methods
menu pairs rice with 4 and soup with 2. menu["rice"] = 5 puts 5 in place of 4. The name rice stays. soup is still 2. Until you add a new name, the length stays 2.
menu["bread"] = 1 writes a name that was not there. bread comes in with 1, and the length becomes 3. A new number on an old name does not grow the menu. A new name does.
menu = {"rice": 4, "soup": 2}
menu["rice"] = 5
menu["bread"] = 1
print(menu["rice"])
print(len(menu))
The screen shows 5, then 3. You asked for rice's number and for the length, so those are the two lines.
soup is still 2. It was not printed, because the program never asked for menu["soup"]. Changing rice did not touch soup.
menu.get("soup") reads the 2. menu.get("tea") gives None, and the program does not stop. tea was never a name. menu["tea"] would stop, because the brackets demand a name that is there. get does not store tea. After the read, tea is still absent.
menu = {"rice": 4, "soup": 2}
print(menu.get("soup"))
print(menu.get("tea"))
The screen shows 2, then None. This menu started over: rice is 4 again, soup is 2, and bread from the first program is not here. The length is still 2. None means tea is not a name. It does not mean tea was stored.
📊 Change, add, or read a missing name
| Writing | What happens |
|---|---|
| menu["rice"] = 5 | rice's number changes, and the length stays |
| menu["bread"] = 1 | a new name comes in, and the length grows |
| menu.get("tea") | None, and the program does not stop |
| menu["tea"] | the program stops |
The next page puts a group inside a value. This page changes a number, adds one name, and reads a missing name without stopping.
What the two menus show
- What does the first program write?
- After that program, what number is still with soup?
- What does the second program write?
- What happens if you write menu["tea"]?
rice is 5, tea was never stored
The first screen is 5, then 3. soup is still 2. The second screen is 2, then None, on a fresh menu that never received bread. menu.get("tea") does not store tea. menu["tea"] stops. The next page puts a group inside a value.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top