Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The Python Workshop Second Edition

You're reading from   The Python Workshop Second Edition Write Python code to solve challenging real-world problems

Arrow left icon
Product type Paperback
Published in Nov 2022
Publisher Packt
ISBN-13 9781804610619
Length 600 pages
Edition 2nd Edition
Languages
Arrow right icon
Authors (5):
Arrow left icon
Mario Corchero Jiménez Mario Corchero Jiménez
Author Profile Icon Mario Corchero Jiménez
Mario Corchero Jiménez
Andrew Bird Andrew Bird
Author Profile Icon Andrew Bird
Andrew Bird
Corey Wade Corey Wade
Author Profile Icon Corey Wade
Corey Wade
Graham Lee Graham Lee
Author Profile Icon Graham Lee
Graham Lee
Dr. Lau Cher Han Dr. Lau Cher Han
Author Profile Icon Dr. Lau Cher Han
Dr. Lau Cher Han
+1 more Show less
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Chapter 1: Python Fundamentals – Math, Strings, Conditionals, and Loops 2. Chapter 2: Python Data Structures FREE CHAPTER 3. Chapter 3: Executing Python – Programs, Algorithms, and Functions 4. Chapter 4: Extending Python, Files, Errors, and Graphs 5. Chapter 5: Constructing Python – Classes and Methods 6. Chapter 6: The Standard Library 7. Chapter 7: Becoming Pythonic 8. Chapter 8: Software Development 9. Chapter 9: Practical Python – Advanced Topics 10. Chapter 10: Data Analytics with pandas and NumPy 11. Chapter 11: Machine Learning 12. Chapter 12: Deep Learning with Python 13. Chapter 13: The Evolution of Python – Discovering New Python Features 14. Index 15. Other Books You May Enjoy

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.

You have been reading a chapter from
The Python Workshop Second Edition - Second Edition
Published in: Nov 2022
Publisher: Packt
ISBN-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.
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 $19.99/month. Cancel anytime