Arrays: Dictionaries

Let's move on to more complex data storage structures – dictionaries.

` ˙⋆˖⁺‧₊☽◯☾₊‧⁺˖⋆˙ `

A dictionary is a collection of key-value pairs. Each key is unique, and it maps to a value. Dictionaries are created by placing key-value pairs inside curly braces «{ }», with a colon «:» separating keys and values, and commas «,» separating each pair.

#Example: Creating a dictionary student = {"name": "Hermione", "age": 18, "grade": "A"} print(student)

In this example, a dictionary named student is created with three key-value pairs: "name" mapped to "Hermione", "age" mapped to 18, "grade" mapped to "A".

Accessing Dictionary Values

You can access values in a dictionary by using their keys. Use square brackets «[ ]» with the key to retrieve the corresponding value.

#Example: Accessing dictionary values student = {"name": "Hermione", "age": 18, "grade": "A"} print(student["name"]) # Output: Hermione print(student["age"]) # Output: 18 print(student["grade"]) # Output: A

In this example, values are accessed by their keys: "name" for "Hermione", "age" for 18, and "grade" for "A".

Modifying Dictionary Values

Dictionaries are mutable, meaning you can change their values. You can modify values by accessing them through their keys and assigning a new value.

#Example: Modifying dictionary values student = {"name": "Hermione", "age": 18, "grade": "A"} student["age"] = 20 print(student) # Output: {"name": "Hermione", "age": 20, "grade": "A"}

In this example, the value associated with the key "age" is changed from 18 to 20.

Adding and Removing Dictionary Items

You can add new key-value pairs to a dictionary or remove existing ones. Use a new key with the assignment operator = to add a pair, and use the del statement to remove a pair.

#Example: Adding and removing dictionary items student = {"name": "Hermione", "age": 18, "grade": "A"} student["major"] = "Charms" # Adding a new key-value pair print(student) # Output: {"name": "Hermione", "age": 25, "grade": "A", "major": "Charms"} del student["grade"] # Removing a key-value pair print(student) # Output: {"name": "Hermione", "age": 25, "major": "Charms"}

In these examples, a new key-value pair "major": "Charms" is added to the student dictionary, and the "grade" key-value pair is removed.

Practical Application

In the Chamber of Enchantment, you will learn to use dictionaries. These powerful tools allow you to map keys to values, enabling complex data storage and retrieval.

⋆˖⁺‧₊ Create a dictionary to store information about a spellbook. Include keys for "title", "author", "pages". Display the dictionary. ₊‧⁺˖⋆

Sample Output:
{'title': 'Grimoire of the Ancients', 'author': 'Merlin', 'pages': 394}
#Type your code below: