Python Dictionary Exercises

Let’s check out some exercises that will help understand dictionaries better.

Exercise 8-a: Python Dictionary Value by Key

Dictionaries don't have index orders, so speaking about them regarding their first item or last item is not very correct. Next time you print a dictionary it may have a different order than you saw before. Instead they have keys, and we can use keys to call their values.


When was Plato born?


dict[“born”]

Correct syntax to call a dictionary’s value is its key inside brackets next to its name.

 

answer_1 = dict["born"]

Exercise 8-b: Editing Python Dictionaries

Change Plato's birth year from B.C. 427 to B.C. 428.


You can just use -428 unless you’d like to use a string format such as: “B.C. 428”

 

In dictionaries later values will always override previous values for the same key.

If you type the new value for the key you’d like to change it will be replaced.

To address a specific key in dictionaries:
dict[“key”]

dict["born"] = -428

Exercise 8-c: Adding a List to Python Dictionary (Nested Data)

Dictionaries can have nested data too. Also, you can add a new key to a dictionary as they are mutable (changeable). Try to add the key "work" to dict with values shown below.


"work": ["Apology", "Phaedo", "Republic", "Symposium"]


All you have to do is call the dict with key “work” and assign the list to it.

dict["work"] = ["Apology", "Phaedo", "Republic", "Symposium"]

Need More Exercises?

Check out Holy Python AI+ for amazing Python learning tools.

*Includes 14 more programming languages, inspirational tools and 1-on-1 consulting options.
Umut Sagir
Finance & Data Science Professional,
Founder of HolyPython