Reader small image

You're reading from  The Python Workshop Second Edition - Second Edition

Product typeBook
Published inNov 2022
Reading LevelN/a
PublisherPackt
ISBN-139781804610619
Edition2nd Edition
Languages
Right arrow
Authors (5):
Corey Wade
Corey Wade
author image
Corey Wade

Corey Wade, M.S. Mathematics, M.F.A. Writing & Consciousness, is the founder and director of Berkeley Coding Academy where he teaches Machine Learning and AI to teens from all over the world. Additionally, Corey chairs the Math Department at Berkeley Independent Study where he has received multiple grants to run after-school coding programs to help bridge the tech skills gap. Additional experiences include teaching Natural Language Processing with Hello World, developing Data Science curricula with Pathstream, and publishing statistics and machine learning models with Towards Data Science, Springboard, and Medium.
Read more about Corey Wade

Mario Corchero Jiménez
Mario Corchero Jiménez
author image
Mario Corchero Jiménez

Mario Corchero Jiménez is a senior software developer at Bloomberg. He leads the Python infrastructure team in London, enabling the company to work effectively in Python and building company-wide libraries and tools. His professional experience is mainly in C++ and Python, and he has contributed some patches to multiple Python open source projects. He is a PSF fellow, having received the Q3 2018 PSF Community Award, is vice president of Python Espaa (the Python Spain association), and has served as Chair of PyLondinium, PyConES17, and PyCon Charlas at PyCon 2018. Mario is passionate about the Python community, open source, and inner source.
Read more about Mario Corchero Jiménez

Andrew Bird
Andrew Bird
author image
Andrew Bird

Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".
Read more about Andrew Bird

Dr. Lau Cher Han
Dr. Lau Cher Han
author image
Dr. Lau Cher Han

Dr Lau Cher Han is a Chief data scientist, and currently the CEO of LEAD, an institution that provides programs on data science, full stack web development, and digital marketing. Well-versed in programming languages: JavaScript, Python, C# and so on he is experienced in web frameworks: MEAN Stack, ASP.NET, Python Django and is multilingual, speaking English, Chinese, Bahasa fluently. His knowledge of Chinese spreads even into its dialects: Hokkien, Teochew, and Cantonese.
Read more about Dr. Lau Cher Han

Graham Lee
Graham Lee
author image
Graham Lee

Graham Lee is an experienced programmer and writer. He has written books including Professional Cocoa Application Security, Test-Driven iOS Development, APPropriate Behaviour and APPosite Concerns. He is a developer who's been programming for long enough to want to start telling other people about the mistakes he's made, in the hope that they'll avoid repeating them. In his case, this means having worked for about 12 years as a professional. His first programming experience can hardly be called professional at all: as it was in BASIC, on a Dragon 32 microcomputer.
Read more about Graham Lee

View More author details
Right arrow

Dictionary keys and values

A Python dictionary is an unordered collection that contains keys and values. Dictionaries are written with curly brackets, and the keys and values are separated by colons.

Have a look at the following example, where you store the details of an employee:

employee = {
  'name': "Jack Nelson",
  'age': 32,
  'department': "sales"
}

Python dictionaries contain key-value pairs. They simply map keys to associated values, as shown here:

Figure 2.12 – Mapping keys and values in Python dictionaries

Figure 2.12 – Mapping keys and values in Python dictionaries

Dictionaries are like lists. They both share the following properties:

  • Both can be used to store values
  • Both can be changed in place and can grow and shrink on demand
  • Both can be nested: a dictionary can contain another dictionary, a list can contain another list, and a list can contain a dictionary and vice versa

The main difference between lists and dictionaries is how elements are accessed. List elements are accessed by their position index, which is [0,1,2…], while dictionary elements are accessed via keys. Therefore, a dictionary is a better choice for representing collections, and mnemonic keys are more suitable when a collection’s items are labeled, as in the database record shown in Figure 2.13. The database here is equivalent to a list, and the database list contains a record that can be represented using a dictionary. Within each record, there are fields to store respective values, and a dictionary can be used to store a record with unique keys mapped to values:

Figure 2.13 – A sample database record

Figure 2.13 – A sample database record

There are, however, a few rules that you need to remember with Python dictionaries:

  • Keys must be unique – no duplicate keys are allowed
  • Keys must be immutable – they can be strings, numbers, or tuples

You will work with dictionaries and store a record in the next exercise.

Exercise 29 – using a dictionary to store a movie record

In this exercise, you will be working with a dictionary to store movie records, and you will also try and access the information in the dictionary using a key. The following steps will enable you to complete this exercise:

  1. Open a Jupyter Notebook.
  2. Enter the following code in a blank cell:
    movie = {
      "title": "The Godfather",
      "director": "Francis Ford Coppola",
      "year": 1972,
      "rating": 9.2
    }

Here, you have created a movie dictionary with a few details, such as title, director, year, and rating.

  1. Access the information from the dictionary by using a key. For instance, you can use 'year' to find out when the movie was first released using bracket notation:
    print(movie['year'])

Here’s the output:

1972
  1. Now, update the dictionary value:
    movie['rating'] = (movie['rating'] + 9.3)/2
    print(movie['rating'])

The output is as follows:

9.25

As you can see, a dictionary’s values can also be updated in place.

  1. Construct a movie dictionary from scratch and extend it using key-value assignment:
    movie = {}
    movie['title'] = "The Godfather"
    movie['director'] = "Francis Ford Coppola"
    movie['year'] = 1972
    movie['rating'] = 9.2

As you may have noticed, similar to a list, a dictionary is flexible in terms of size.

  1. You can also store a list inside a dictionary and store a dictionary within that dictionary:
    movie['actors'] = ['Marlon Brando', 'Al Pacino',  
      'James Caan']
    movie['other_details'] = {
      'runtime': 175,
      'language': 'English'
    }
    print(movie)

The output is as follows:

Figure 2.14 – Output while storing a dictionary within a dictionary

Figure 2.14 – Output while storing a dictionary within a dictionary

So far, you have learned how to implement nesting in both lists and dictionaries. By combining lists and dictionaries creatively, we can store complex real-world information and model structures directly and easily. This is one of the main benefits of scripting languages such as Python.

Activity 7 – storing company employee table data using a list and a dictionary

Remember the employee dataset, which you previously stored using a nested list? Now that you have learned about lists and dictionaries, you will learn how to store and access our data more effectively using dictionaries that contain lists.

The following table contains employee data:

Figure 2.15 – Employee data in a table

Figure 2.15 – Employee data in a table

Follow these steps to complete this activity:

  1. Open a Jupyter notebook (you can create a new one or use an existing one).
  2. Create a list named employees.
  3. Create three dictionary objects inside employees to store the information of each employee.
  4. Print the employees variable.
  5. Print the details of all employees in a presentable format.
  6. Print only the details of Sujan Patel.

The output is as follows:

Figure 2.16 – Output when we only print the employee details of Sujan Patel

Figure 2.16 – Output when we only print the employee details of Sujan Patel

Note

The solution for this activity can be found in Appendix on GitHub.

Previous PageNext Page
You have been reading a chapter from
The Python Workshop Second Edition - Second Edition
Published in: Nov 2022Publisher: PacktISBN-13: 9781804610619
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (5)

author image
Corey Wade

Corey Wade, M.S. Mathematics, M.F.A. Writing & Consciousness, is the founder and director of Berkeley Coding Academy where he teaches Machine Learning and AI to teens from all over the world. Additionally, Corey chairs the Math Department at Berkeley Independent Study where he has received multiple grants to run after-school coding programs to help bridge the tech skills gap. Additional experiences include teaching Natural Language Processing with Hello World, developing Data Science curricula with Pathstream, and publishing statistics and machine learning models with Towards Data Science, Springboard, and Medium.
Read more about Corey Wade

author image
Mario Corchero Jiménez

Mario Corchero Jiménez is a senior software developer at Bloomberg. He leads the Python infrastructure team in London, enabling the company to work effectively in Python and building company-wide libraries and tools. His professional experience is mainly in C++ and Python, and he has contributed some patches to multiple Python open source projects. He is a PSF fellow, having received the Q3 2018 PSF Community Award, is vice president of Python Espaa (the Python Spain association), and has served as Chair of PyLondinium, PyConES17, and PyCon Charlas at PyCon 2018. Mario is passionate about the Python community, open source, and inner source.
Read more about Mario Corchero Jiménez

author image
Andrew Bird

Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".
Read more about Andrew Bird

author image
Dr. Lau Cher Han

Dr Lau Cher Han is a Chief data scientist, and currently the CEO of LEAD, an institution that provides programs on data science, full stack web development, and digital marketing. Well-versed in programming languages: JavaScript, Python, C# and so on he is experienced in web frameworks: MEAN Stack, ASP.NET, Python Django and is multilingual, speaking English, Chinese, Bahasa fluently. His knowledge of Chinese spreads even into its dialects: Hokkien, Teochew, and Cantonese.
Read more about Dr. Lau Cher Han

author image
Graham Lee

Graham Lee is an experienced programmer and writer. He has written books including Professional Cocoa Application Security, Test-Driven iOS Development, APPropriate Behaviour and APPosite Concerns. He is a developer who's been programming for long enough to want to start telling other people about the mistakes he's made, in the hope that they'll avoid repeating them. In his case, this means having worked for about 12 years as a professional. His first programming experience can hardly be called professional at all: as it was in BASIC, on a Dragon 32 microcomputer.
Read more about Graham Lee