Loading...

Python Dictionaries

A dictionary pairs a name with a value. In cup, the name lida goes with tea, and the name guest goes with water. A colon sits between the name and the value. A comma separates one pair from the next. Curly braces hold the pairs.

You read with the name, not with a place number. cup["lida"] is tea. cup["guest"] is water. cup[0] stops the program, because 0 is not a name in cup.

tea for lida, water for guest

python
cup = {"lida": "tea", "guest": "water"}

print(cup["lida"])
print(cup["guest"])

The screen shows tea, then water. lida was asked first, so tea comes first. The order on the screen is the order of the names you asked for, not a place count.

len(cup) is 2, one for each name. An empty dictionary is {}, and its length is 0. This program does not use the empty one. It prints the length, then tea again through the name lida.

two names, then tea

python
cup = {"lida": "tea", "guest": "water"}

print(len(cup))
print(cup["lida"])

The screen shows 2, then tea. guest is still paired with water. The second line did not ask for guest, so water is not written.

Write the same name twice and the later value is the one that stays. cup = {"lida": "tea", "lida": "water"} keeps water for lida. tea is gone. The length is 1, because there is only one name.

the later value stays

python
cup = {"lida": "tea", "lida": "water"}

print(cup["lida"])
print(len(cup))

The screen shows water, then 1. The first tea did not survive the second writing of lida. One name, one value.

cup["soup"] stops the program. soup was never written as a name, so there is no value to read. That line is not in the programs above.

The next page reads the pairs in more ways and changes a value. This page writes the pairs and reads by name.

Three screens

  1. What does the first program write?
  2. What does the second program write?
  3. What does the third program write?
  4. What happens if you write cup["soup"]?

tea for lida

The first screen is tea, then water. The second is 2, then tea. The third is water, then 1, because the later lida replaced tea and only one name remains. cup[0] stops, and cup["soup"] stops. The next page reads the pairs in more ways and changes a value.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
4
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 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