1️⃣

9.1 Initializing Dictionaries

Initializing Dictionaries

Dictionaries are another way besides lists to store data in Python. Let's think of dictionaries in real life - they store words and their corresponding definitions. Dictionaries in Python are the same concept, except instead of storing words and definitions, they store keys and values as pairs.
Say I want to store the names and addresses of people on my contacts list. I could store them in a dictionary like this:
Key:
“John Doe”
"Jane Smith”
"Daisy Johnson”
Value:
"1234 Main St”
"5678 Market St”
“1357 Wall St”
In Python syntax, it would look like this:
contacts = { "John Doe" : "1234 Main St", "Jane Smith" : "5678 Market St", "Daisy Johnson" : "1357 Wall St" }
💡
While you can write all the key-value pairs on one line, it's generally better style and easier to read if you write it on multiple lines.
As you see, the key is separated from the value by a colon, and each key-value pair is separated by a comma, just like in a list. Also, notice that, unlike a list, dictionaries are enclosed by curly braces, not square brackets.
 
You can also change the type of certain iterables into a dictionary using dict(). Notice that you have to use a list of lists. The inner lists are the key-value pairs in the dictionary (also called entries)
# creating a dict form a list of lists my_list = [["key1", "value1"], ["key2", "value2"], ["key3", "value3"]] my_dict = dict(my_list) print(my_dict) # Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
View code on GitHub.

Limits on Keys and Values

Any type can be used as keys of a dictionary, except for mutable types. They are called mutable because they can be directly changed without creating a copy, and some of these include dictionaries and lists. Basically, don't use dictionaries or lists as your keys.
The reason why the keys have to be immutable is that, if they were to change, their hash would change. (Don't worry about hashing. Just know it is the internal process for finding the location of the key.)
Any type can be used as the value since the value doesn't affect hashing

Previous Chapter

 
⚖️
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.