Dictionaries
Now we'll dive into a bit more advanced data structures, dictionaries! A dictionary is like a list, except it uses curly brackets { } instead of square brackets [ ]— but most importantly, dictionaries also differ in that they store values with keys, and can accept several data types. A dictionary can be highly versatile, and can not only be used for data storage, but for more complex algorithms like hashmaps, which we'll go over later. Most interestingly, we can have dictionaries with dictionaries within them, and even lists as well! It's important to mention that keys and values have a colon ' : ' separator between them.
Here's a simple example of a dictionary:
this_is_my_dictionary = {"name": "John", "age": 22}
In lists, we used a process called indexing, and the index notation format to access values, eg; my_list[3]. With dictionaries, we use a similar process called key access, and the key notation format to access values.
The main difference is that we use keys, instead of solely integers that refer to position, to select values from a dictionary— and not to confuse you, but a key in a dictionary can also be an integer =).
For example, in this_is_my_dictionary above, you'll see the value "John" belongs to the key, "name". As well as the value 22, belongs to the key, "age". This is what key notation would look like for accessing a value for a specific key in a dictionary:
name_value = this_is_my_dictionary['name']
print(name_value)
# Output: "John"
Try printing the "age" value in the code editor below:
age_value = this_is_my_dictionary['age']
print(age_value)
# Output: 22
Now we'll look over a more intricate dictionary, that's a bit larger and complex.
this_is_my_dictionary = {"name": "John", "age": 22, "likes": ["Exercise", "Cooking", "Coding"]}
We see something in this dictionary that we haven't seen before, a list as the value to a key. Let's try accessing the 1st index of John's likes using a mix of key notation and index notation!
likes = this_is_my_dictionary['likes']
print(likes)
# Output:# ["Exercise", "Cooking", "Coding"]
likes_first_index = likes[1]
print(likes_first_index)
# Output:# "Cooking"