Level III
Play with dictionaries
Now that you know how to deal with lists, let’s show you the dictionaries. Dictionaries are another way to store values. Imagine a real dictionary, there are some “words” and each of them have a “description”, right? Now, let’s adapt our vocabulary to Python, these words from the dictionary are called “keys” and the descriptions are “values”.
Lists required squared braces, [], remember? Dictionaries require {}, curly ones. Thus, this is an empty dictionary, stored in a variable called “dic”:
Keys can be numbers, strings, booleans…These will be separated from the values with “:”.
Dictionaries can be very useful when we want to store several values to access them quickly.
This is how we explore keys and values:
This is how we add values to dictionaries:
This is how we merge dictionaries:
There are some things you might not be able to remember. Don’t worry! It is helpful to know that they exist, so you google it if you need to use it.
Now you know many things about dictionaries. How would you get values (descriptions) from them? Just ask for the key (word), as if you were going through the pages of a printed dictionary.
As you’ve just seen, in order to delete an item you need to do it by key, not by value!
Remember
Dictionaries do not work as lists; lists have order and you can access the values by position with indices. Dictionaries do not have any order, so there are no indices here.
Previous lesson
Play with loops inside loops
Next lesson
Play with functions