Learning about dictionaries
In Python, a dictionary is an unordered, mutable, and indexed data structure. It stores data in key-value pairs and provides a way to retrieve the value for any given key. Dictionaries are an important and versatile data structure in Python and are widely used in various kinds of programming tasks.
Creating a Dictionary
A dictionary in Python is defined by key-value pairs enclosed in curly braces {}
, with pairs separated by commas. Each key-value pair is separated by a colon :
. Here’s an example:
student = { "name": "Alice", "age": 20, "courses": ["math", "comp sci"] }
Accessing Values
You can access the value for a given key using square brackets []
:
print(student["name"]) # prints: Alice
If you try to access a key that does not exist in the dictionary, Python will raise a KeyError. To avoid this, you can use the get
method, which returns None
if the key is not found.
print(student.get("grade")) # prints: None
Adding and Changing Items
You can add a new key-value pair to a dictionary by assigning a value to a new key:
student["grade"] = "A"
You can also change the value of an existing key the same way:
student["age"] = 21
Removing Items
The del
keyword can be used to remove a key-value pair from a dictionary:
del student["age"]
Looping Through a Dictionary
You can loop through a dictionary to access its keys and values:
for key in student: print(key, student[key])
This will print each key and its corresponding value.
In summary, dictionaries in Python are a powerful tool for storing and managing data. They allow you to connect pieces of related information and efficiently access or modify them.