Level 1
0 / 100 XP

Dictionaries

In Python, a dictionary is a data structure that stores an unordered collection of items. Dictionaries are also known as associative arrays or hash maps. In a dictionary, each item has a key and a value. The key is used to access the item, and the value is the item itself. In Python, you can create a dictionary using curly braces {} and the : character to separate the keys and values. Here are some examples of creating dictionaries in Python:

Text
# Create an empty dictionary my_dict = {} # Create a dictionary of numbers numbers = {1: "one", 2: "two", 3: "three"} # Create a dictionary of strings colors = {"red": "#FF0000", "green": "#00FF00", "blue": "#0000FF"} # Create a dictionary of mixed data types mixed = {1: "one", "two": 2, 3.0: [3, 4, 5]}

As you can see, a dictionary can store items of any data type, including other dictionaries.

Accessing and Modifying Dictionary Items

In Python, you can access the items in a dictionary using the key. To access an item in a dictionary, use the square bracket notation [] and specify the key of the item you want to access. Here are some examples of accessing items in a dictionary:

Python
# Access an item in a dictionary print(numbers[1]) # Output: "one" # Access a range of items in a dictionary (this will cause an error) print(numbers[1:3]) # Output: TypeError: unhashable type: 'slice'

As you can see, you can access the items in a dictionary using the key, but you cannot access a range of items in a dictionary like you can with a list or a tuple. This is because dictionaries are unordered, so the items in a dictionary do not have a specific order or index.

To modify an item in a dictionary, use the square bracket notation [] and specify the key of the item you want to modify. Then, use the assignment operator = to assign a new value to that item. Here are some examples of modifying items in a dictionary:…