Dictionaries
Python dictionaries (also commonly referred as dicts), are another structure used to store data. Dicts are non sequential, storing what we call key-value pairs. This means that the indexes, instead of being sequential numbers, are defined when storing the data. An index can be a number, a string, an object.
Creating a dict, accessing and modifying data
To create a dict, we use curly brackets ({}
). Elements follow the "key" : "value"
format. Let’s see an example so that it’s more clear:
student = {"name": "Joseph", "age": 20, "grade": 9.2}
print(student)
> {'name': 'Joseph', 'age': 20, 'grade': 9.2}
As you can imagine, it’s possible to create an empty dict, definind only the brackets, without elements inside of it:
empty_dict = {}
print(empty_dict)
> {}
To access data in a dict, we use the same notation used for lists. The difference is that, instead of the numeric index on lists, we use the key to retrieve a value:
print(aluno["name"])
print(aluno["age"])
> Joseph
> 20
If we try to access a key that’s not in the dict, Python raises an error:
print(student["weight"])
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> KeyError: 'weight'
To modify data, we, again, use the same notation used for lists. Just use the key where you want to change the value and assign the new value. The inclusion of a new key-value pair in a dict is done in the same way, by using a key that is not on the dict:
student["grade"] = 8.2
student["weight"] = 74
print(student)
> {'age': 20, 'name': 'Joseph', 'grade': 8.2, 'weight': 74}
Note how the "weight"
key and its value were added, and the value for the "grade"
key was changed.
To remove a key-value pair, we use del
, with the dict and the reference for the key. To delete all pairs in a dict, we use the clear()
method, called from the dict:
del studen["age"]
print(student)
student.clear()
print(student)
> {'name': 'Joseph', 'grade': 8.2, 'weight': 74}
> {}
Useful functions to work with dicts
Some functions we use with lists also work with dicts. It’s the case of len()
, which will return the quantity of key-value pairs on the dict. Let’s also redefine the student
dict, which we cleared on our last example:
student = {"name": "Joseph", "age": 20, "grade": 9.2}
print(len(student))
> 3
Another thing that also works with dicts is checking if a key exists in it through the in
keyword:
print("age" in student)
print("weight" in student)
> True
> False
We also have other methods specific to dicts. Let’s see some of them:
get()
The get()
method is really useful to avoid inexistent key errors. It receives two parameters, the first one is the key that we want to retrieve, and a default return value. If the key exists in the dict, this function will return its value. If it doesn’t exist, it will return the default value passed as a parameter, or None
, if no default return value is provided:
student = {"name": "Joseph", "age": 20, "grade": 9.2}
print(aluno.get("name"))
print(aluno.get("weight"))
print(aluno.get("weight", "Not defined"))
> Joseph
> None
> Not defined
items(), keys() and values()
The items()
function returns a list with tuples, where the first item of each tuple is a key, and the second its related value. The keys()
function returns a list with all keys on the dict. And the values()
function returns a list with all values in the dict:
print(student.items())
print(student.keys())
print(student.values())
> dict_items([('age', 20), ('grade', 9.2), ('name', 'Joseph')])
> dict_keys(['age', 'grade', 'name'])
> dict_values([20, 9.2, 'Joseph'])
update()
The update()
function is called from a dict, and receives another dict as parameter. It inserts the pairs of the dict passed as a parameter and inserts the key-value pairs on the dict from which the function was called. If keys on the dict that was passed as parameter exist in the original dict, the value for these keys in the original dict will be updated with the values on the dict passed as the parameter:
original_student = {"name": "Joseph", "age": 20, "grade": 9.2}
student_update_info = {"weight": 75, "grade": 8.7}
original_student.update(original_student)
print(original_student)
> {'name': 'Joseph', 'age': 20, 'grade': 8.7, 'weight': 75}
As you can see, the key-value pair for "weight"
was added and the value for "grade"
was modified.
Conclusion
In this chapter, we learned about dicts and their differences to lists and tuples. We saw how to create a dict, update and access its data and also functions that we can use to make our life easier when working with them. In the next chapter we will learn about sets.