thisdict = {
"city": "Evry",
"model": "Linear Regression",
"year": 1977
}9-Dictionary
Link to the Google Colaboratory notebook: 9-Dictionary
Dictionaries are used to store data values in key:value pairs.
Length
You can access the number of pairs of (key, value) with the len command:
example_dict = {
"city": "Evry",
"model": "Linear Regression",
"year": 1977
}
print(len(example_dict))3
Access a dictionary
To get the content of a dictionary, you need to know a specific key. Given a key, you can access the value:
content = {"name": "Evry"}
print(content["name"])
# You can also use the `.get`
print(content.get("name"))Evry
Evry
You can also list the elements of the dictionary using .keys() command:
example_dict = {
"city": "Evry",
"model": "Linear Regression",
"year": 1977
}
print(example_dict.keys())dict_keys(['city', 'model', 'year'])
You can also access the value of a dictionary with the .values() command:
print(example_dict.values())dict_values(['Evry', 'Linear Regression', 1977])
You can access both the values and the keys with the .items command.
Note that it will return a tuple of (key, value):
print(example_dict.items())dict_items([('city', 'Evry'), ('model', 'Linear Regression'), ('year', 1977)])
Check element in dictionary
You can check if an element is in the keys of a dictionary:
example_dict = {
"city": "Evry",
"model": "Linear Regression",
"year": 1977
}
print("a" in example_dict)
print("city" in example_dict)False
True
Update
The update() method will update the dictionary with the items from the given argument.
The argument must be a dictionary with the updated {key: value}.
example_dict = {
"city": "Evry",
"model": "Linear Regression",
"year": 1977
}
example_dict.update({"year" : 77})
print(example_dict){'city': 'Evry', 'model': 'Linear Regression', 'year': 77}
You can also add an element to a dictionary by just refering the new key as following:
example_dict = {"test": -1}
example_dict["new_key"] = "new_value"
print(example_dict){'test': -1, 'new_key': 'new_value'}
You can remove an element of the dictionary using the pop function:
example_dict = {
"city": "Evry",
"model": "Linear Regression",
"year": 1977
}
example_dict.pop("year")
print(example_dict){'city': 'Evry', 'model': 'Linear Regression'}
Loop
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
for key in example_dict:
print(key)
for key in example_dict.keys():
print(key)city
model
city
model
for key in example_dict:
print(example_dict[key])
for key in example_dict.values():
print(key)Evry
Linear Regression
Evry
Linear Regression
You can also iterate with both the keys and the values using the items command:
for key, value in example_dict.items():
print(key, value)city Evry
model Linear Regression