2️⃣

9.2 Why Dictionaries?

Why Dictionaries?

Dictionaries allow for elegant and intuitive code writing.
You might remember the Grocery List exercise from
📋
Ch. 6 Lists
. In that exercise, you needed to make several lists to store quantities that were related to each other, such as the name of a grocery item, its price, and its quantity. You can use a single dictionary to do this instead of using multiple lists. It also makes more sense to use a dictionary for this because it explicitly associates the grocery item with its price and quantity.
Similarly, you can make a contacts list with a dictionary to map a person's name to their address.
# dictionaries as an alternative to parallel lists names = [ "Jane Doe", "John Williams", "Alex Summers" ] addresses = ["1234 Main St", "5678 Market Pl", "1357 Wall St"] # better solution: make a dictionary to # explicitly associate a name with an address # this is also called mapping a key to a value contacts = { "Jane Doe": "1234 Main St", "John Williams": "5678 Market Pl", "Alex Summers": "1357 Wall St" }
Another example is with using if-else blocks. A couple lines of if statements can get compressed into two lines. You are essentially spitting out multiple different outputs for multiple different inputs.
Implementation 1 using if statements
# implementation 1 using if statements value = 10 if value == 10: print("Tom") elif value == 20: print("Daniel") elif value == 30: print("Elizabeth")
Implementation 2 using dictionary
# implementation 2 using dictionary dict1 = {10: "Tom", 20: "Daniel", 30: "Elizabeth"} print(dict1[value])
Finally, dictionaries are much more flexible than lists because you aren't limited to using ordered indices to access, update, or retrieve elements.
View code on GitHub.
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.