Night 18: Your pet's ID card
لقد أنهيت هذه الليلة بالفعل باستخدام Python أو الشيفرة الكاذبة. وهي تُحتسب لكلتيهما. تدرّب مرة أخرى إن شئت.
Tonight: your pet's ID card
- Your pet needs an ID card with its name, age and food.
- You will learn one thing: dictionaries.
Words for tonight
| Word | Meaning |
|---|---|
| dictionary | a set of keys, each with a value |
| key | the name you look up, like "age" |
| value | what is stored for a key, like 2 |
Make a dictionary
- Use
{ }. Writekey: valuepairs, with commas between them.
pet = {"name": "Kit", "age": 2, "food": "fish"}
print(pet["name"])
print(pet["food"])
| Key | Value |
|---|---|
"name" |
"Kit" |
"age" |
2 |
"food" |
"fish" |

List or dictionary?
| List | Dictionary |
|---|---|
["Kit", 2, "fish"] |
{"name": "Kit", "age": 2, "food": "fish"} |
find by position: pet[1] |
find by key: pet["age"] |
| good for many things of one kind | good for many facts about one thing |
Change and add
- Use the key in
[ ]with=to change a value, or to add a new key.
pet = {"name": "Kit", "age": 2}
pet["age"] = 3
pet["toy"] = "ball"
print(pet)
Is the key there?
inchecks if a dictionary has a key.
pet = {"name": "Kit", "age": 2}
if "toy" in pet:
print(pet["toy"])
else:
print("No toy yet")
- Now make your pet's ID card!
الصعوبة 2/5 · 140 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
Make a dictionary pet with three keys: "name" هي "Kit", "age" هي 2, "food" هي "fish". Print the pet's name.
اضغط تشغيل لرؤية المخرجات هنا.
الصعوبة 2/5 · 140 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
It is Kit's birthday! Add 1 to pet["age"]. Then print the new age: 3.
اضغط تشغيل لرؤية المخرجات هنا.
الصعوبة 2/5 · 140 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
Kit has a new toy. Add the key "toy" with the value "ball". Then print Kit plays with ball, using the dictionary.
اضغط تشغيل لرؤية المخرجات هنا.
الصعوبة 3/5 · 200 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
Read a key with input(). If the key is in pet, print its value. If not, print No such thing.
اضغط تشغيل لرؤية المخرجات هنا.