Learn how to use dictionaries to store data in your Python programs.
A dictionary is an unordered data structure that stores key-value pairs. Dictionaries enable us to access values with their associated key, as opposed to lists, which use indices to access values. Dictionaries are created with curly brackets:
You can add initial key-value pairs to a dictionary like this:
A few things to note about this structure:
:
The keys and values in a single dictionary can be multiple data types. For example, we can add the key-value pair 225: 15
to this dictionary even though the current entries are strings.
Additionally, the key and value data types can be different themselves: 225: "perfect square"
is a valid key-value pair. One important note is that a key cannot be a mutable data type, such as a list or a set, while a value can be a mutable data type.
To access a value in a dictionary, we use its key. The general structure for accessing a value in a dictionary is like this: dictionary_name[key]
.
You can use a for loop to iterate through a dictionary and access each individual value by using the in
keyword:
This for loop says “for every key in my_dictionary
, print out the key’s value.” Here’s the output of the above for loop:
You can add items to a dictionary using this basic structure: dictionary_name[key] = value
. Let’s add another key-value pair to my_dictionary
:
Now, 256: 16
is a key-value pair in my_dictionary
.
You can update the value of a key in a dictionary by accessing the key and assigning it a new value:
Take a look at the example dictionary in the code editor below. Explore with these guiding tasks:
Try creating your own dictionary in the editor below. Your dictionary can be a phone book, a collection of square roots, a weekly dinner menu…the possibilities are endless! Master the basics of dictionaries in Python by completing each task below: