Skip to Content
The Python Book
book

The Python Book

by Rob Mastrodomenico
January 2022
Beginner to intermediate
272 pages
6h 51m
English
Wiley
Content preview from The Python Book

9Dictionaries

When we say dictionary in Python, we aren't speaking of the Oxford variety. Dictionaries are used to contain data in a very specific way as they hold key value pairs. What do we mean by key value pairs? For example, we could have a key as first name and a value as Rob. We could also have a key as wins and the value as 21. The key to dictionaries (pun intended) is that to access values we need to have a key associated with it. Let us start with an example about personal details, we may have the following fields: first name, surname, gender, favourite food. This could be written in the form of a dictionary as follows:

image

Its important to note that the name of the dictionary is arbitrary, I used dict as I am not very creative, I could easily have written it as follows:

image

You could argue that the second one is funnier and I would agree, however the name of your dictionary or variable should reflect what you are trying to do as someone will no doubt have to read your code. The problem with us using dict is that dict is a builtin function with Python that means it actually does something. Now, there is nothing to prevent you from using this, however if you override the builtin function dict with your dictionary dict, then you cannot use that within the current environment. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The Quick Python Book, Third Edition

The Quick Python Book, Third Edition

Naomi Ceder, David Fugate
Serious Python

Serious Python

Julien Danjou

Publisher Resources

ISBN: 9781119573319Purchase Link