Dictionaries
In this class, we will delve into dictionaries, which are data structures that store data in the form of key-value pairs.
Dictionary creation Link to heading
Dictionaries can be created using the dict()
function or using {}
curly braces.
Example: Link to heading
# Creating a dictionary with the dict() function
dictionary1 = dict(name="Ana", age=25)
# Creating a dictionary with braces
dictionary2 = {"name": "Ana", "age": 25}
print(dictionary1)
print(dictionary2)
Exit: Link to heading
{'name': 'Ana', 'age': 25}
{'name': 'Ana', 'age': 25}
In this example:
- Two dictionaries are created:
dictionary1
anddictionary2
. - Both dictionaries store the same data: a person’s name and age.
- The first dictionary is created using the
dict()
function. The second dictionary is created using braces{}
.
Access to values Link to heading
The values of a dictionary can be accessed using the key.
Example: Link to heading
dictionary = {"name": "Ana", "age": 25}
name = dictionary["name"]
age = dictionary["age"]
print(name)
print(age)
Exit: Link to heading
Ana
25
In this example:
- The value of the key “name” is accessed and saved in the variable
name
. - The value of the key “age” is accessed and saved in the variable
age
.
Modification of values Link to heading
You can modify the value of a dictionary using the key.
Example: Link to heading
dictionary = {"name": "Ana", "age": 25}
dictionary["age"] = 26
print(dictionary)
Exit: Link to heading
{'name': 'Ana', 'age': 26}
In this example: The value of the “age” key is modified to 26.
Dictionary methods Link to heading
Dictionaries have keys()
and values()
methods that can be used to perform different tasks.
Example: Link to heading
dictionary = {"name": "Ana", "age": 25}
print(dictionary.keys())
print(dictionary.values())
Exit: Link to heading
['name Age']
['Anna', 25]
In this example:
The keys()
method is used to obtain a list of the dictionary keys.
The values()
method is used to obtain a list of the values in the dictionary.
Exercise Link to heading
Create a dictionary that stores a person’s contact information (name, phone, email).