Page Contents
Executive Page Summary
Python dictionaries are a powerful and flexible data structure that allow you to store and manipulate key-value pairs. In this guide, we will cover the basics of Python dictionaries and explore more advanced topics such as dictionary comprehension and nested dictionaries.
A dictionary is an unordered collection of key-value pairs. Each key is unique and maps to a value. Dictionaries are similar to lists, but instead of using integer indices to access elements, they use keys.
You can create a dictionary by enclosing a comma-separated list of key-value pairs in curly braces {}. For example:
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
In this example, we have created a dictionary with three key-value pairs. The keys are "key1", "key2", and "key3", and the corresponding values are "value1", "value2", and "value3".
You can access the value associated with a key in a dictionary by using the key inside square brackets []. For example:
my_dict = {"apple": 1, "banana": 2, "orange": 3}
print(my_dict["banana"])
This will output:
2
If you try to access a key that does not exist in the dictionary, you will get a KeyError.
You can update the value associated with a key in a dictionary by using the key inside square brackets [] and assigning a new value. For example: