☰
Python Across Disciplines
with Python + AI Tool   
×
Table of Contents

1.1.   Introduction 1.2.   About the Author & Contact Info 1.3.   Book Conventions 1.4.   What (Who) is a Programmer? 1.5.   Programming Across Disciplines 1.6.   Foundational Computing Concepts 1.7.   About Python 1.8.   First Steps 1.8.1 Computer Setup 1.8.2 Python print() Function 1.8.3 Comments
2.1. About Data 2.2. Data Types 2.3. Variables 2.4. User Input 2.5. Data Structures (DS)         2.5.1. DS Concepts         2.5.2. Lists         2.5.3. Dictionaries         2.5.4. Others 2.6. Files         2.6.1. Files & File Systems         2.6.2. Python File Object         2.6.3. Data Files 2.7. Databases
3.1. About Processing 3.2. Decisions         3.2.1 Decision Concepts         3.2.2 Conditions & Booleans         3.2.3 if Statements         3.2.4 if-else Statements         3.2.5 if-elif-else Statements         3.2.6 In-Line if Statements 3.3. Repetition (a.k.a. Loops)         3.3.1  Repetition Concepts         3.3.2  while Loops         3.3.3  for Loops         3.3.4  Nested Loops         3.3.5  Validating User Input 3.4. Functions         3.4.1  Function Concepts         3.4.2  Built-In Functions         3.4.3  Programmer Defined Functions 3.5. Libraries         3.5.1  Library Concepts         3.5.2  Standard Library         3.5.3  External Libraries 3.6. Processing Case Studies         3.6.1  Case Studies         3.6.2  Parsing Data
4.1. About Output 4.2. Advanced Printing 4.3. Data Visualization   4.4  Sound
  4.5  Graphics
  4.6  Video
  4.7  Web Output
  4.8  PDFs & Documents
  4.9  Dashboards
  4.10  Animation & Games
  4.11  Text to Speech

5.1 About Disciplines 5.2 Accounting 5.3 Architecture 5.4 Art 5.5 Artificial Intelligence (AI) 5.6 Autonomous Vehicles 5.7 Bioinformatics 5.8 Biology 5.9 Bitcoin 5.10 Blockchain 5.11 Business 5.12 Business Analytics 5.13 Chemistry 5.14 Communication 5.15 Computational Photography 5.16 Computer Science 5.17 Creative Writing 5.18 Cryptocurrency 5.19 Cultural Studies 5.20 Data Analytics 5.21 Data Engineering 5.22 Data Science 5.23 Data Visualization 5.24 Drone Piloting 5.25 Economics 5.26 Education 5.27 Engineering 5.28 English 5.29 Entrepreneurship 5.30 Environmental Studies 5.31 Exercise Science 5.32 Film 5.33 Finance 5.34 Gaming 5.35 Gender Studies 5.36 Genetics 5.37 Geography 5.38 Geology 5.39 Geospatial Analysis ☯ 5.40 History 5.41 Humanities 5.42 Information Systems 5.43 Languages 5.44 Law 5.45 Linguistics 5.46 Literature 5.47 Machine Learning 5.48 Management 5.49 Marketing 5.50 Mathematics 5.51 Medicine 5.52 Military 5.53 Model Railroading 5.54 Music 5.55 Natural Language Processing (NLP) 5.56 Network Analysis 5.57 Neural Networks 5.58 Neurology 5.59 Nursing 5.60 Pharmacology 5.61 Philosophy 5.62 Physiology 5.63 Politics 5.64 Psychiatry 5.65 Psychology 5.66 Real Estate 5.67 Recreation 5.68 Remote Control (RC) Vehicles 5.69 Rhetoric 5.70 Science 5.71 Sociology 5.72 Sports 5.73 Stock Trading 5.74 Text Mining 5.75 Weather 5.76 Writing
6.1. Databases         6.1.1 Overview of Databases         6.1.2 SQLite Databases         6.1.3 Querying a SQLite Database         6.1.4 CRUD Operations with SQLite         6.1.5 Connecting to Other Databases
Built-In Functions Conceptss Data Types Date & Time Format Codes Dictionary Methods Escape Sequences File Access Modes File Object Methods Python Keywords List Methods Operators Set Methods String Methods Tuple Methods Glossary Index Appendices   Software Install & Setup
  Coding Tools:
  A.  Python    B.  Google CoLaboratory    C.  Visual Studio Code    D.  PyCharm IDE    E.  Git    F.  GitHub 
  Database Tools:
  G.  SQLite Database    H.  MySQL Database 


Python Across Disciplines
by John Gordon © 2023

Table of Contents

Table of Contents  »  Chapter 2 : Data (Input) : Data Structures : Dictionaries

Dictionaries

Subscribe Contact


Contents

Overview

Dictionaries in Python are collections of data values stored as key:value pairs. Dictionaries in Python are not indexed like lists; rather they are indexed by the keys of the key:value pairs. Keys in dictionaries must be unique, dictionaries cannot contain duplicate keys, similar to primary keys in databases.

Concept: Dictionary
Full Concepts List: Alphabetical  or By Chapter 

In Python, a dictionary is a collection data type that is mutable, dynamic, and can store an unordered set of key-value pairs. The key in a Python dictionary is unique and acts as an identifier for the associated value, optimizing dictionaries for retrieving data. The values in a dictionary can be of any data type, and a single dictionary can store values of different types. Dictionaries are defined with curly braces {}, with key-value pairs separated by colons and each pair separated by commas. For example, my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'} is a dictionary that contains three key-value pairs. Keys are typically strings, but any immutable type can be used. The flexibility of dictionaries makes them ideal for tasks like data organization, fast data lookup, and data manipulation. They are widely used in applications such as data analysis, web development, and as a way to manage complex data structures in a structured manner.

Concept: Key:Value Pair
Full Concepts List: Alphabetical  or By Chapter 

A key:value pair (also often called name:value pair, attribute:value pair or field:value pair) is a common representation of data in computer systems and applications. Programmers often work with this method of representing data. An example of a key:value pairs might be Make:Ford, Model:F150, where Make and Model are the keys and Ford and F150 are the corresponding values.


The Dictionary Data Structure

Dictionary Attribute Description
Heterogeneous Dictionaries are heterogeneous, that is, they can store different values of different data types at the same time.
Ordered The items in a dictionary are in order and remain that way unless we use Dictionary Methods  to alter that order.
Mutability The items in a dictionary are mutable (changeable), that is, they can be changed, added, and removed after they have been added to the dictionary.
Duplicates Dictionaries cannot have duplicate keys, however values within the dictionary can be duplicated, for example, key1:4444, key1,4444 are not allowed, but key1:4444, key2:4444 are allowed.
Indexing Dictionaries are not indexed like lists, rather they are indexed based on their keys since keys are required to be unique in dictionaries.
Have Methods Because dictionaries are objects, they have methods . You can find a full list of dictionary methods here .
Can Be Nested Dictionaries can contain dictionaries, that is, any dictionary element can contain a dictionary.

Creating Dictionaries

Creating a dictionary requires a variable, the assignment operator (=), and a set of key:value pairs enclosed in curly braces { }. Here is the general form of creating a list:

dictionary_variable = {key1:value, key2:value, ... keyN:value}

Here are several code examples:

# Empty dictionary
d = {}

# Dictionary
simple_d = {"key1": 111111}

# Dictionary
employee = {
  "employee_id": 12345678,
  "first_name": "Bob",
  "last_name": "Smith",
  "department": "Marketing",
  "age": 25,
  "hourly_rate": 23.50,
  "insurance": True
}

# Nested Dictionary
employees = {
  "e1": {
    "employee_id": 23456789,
    "first_name": "Mateo",
    "last_name": "Garcia",
    "department": "CEO",
    "age": 53,
    "hourly_rate": 144.33,
    "insurance": True
  },
  "e2": {
    "employee_id": 34567890,
    "first_name": "Sally",
    "last_name": "Jones",
    "department": "IT",
    "age": 41,
    "hourly_rate": 36.00,
    "insurance": True
  }
}

Code Details:

Accessing Dictionary Items

Let's expand on the code above for creating the dictionaries to demonstrate how to access items in those dictionaries:

# Empty dictionary
d = {}
print(d)

# Simple Dictionary
simple_d = {"key1": 111111}
print(simple_d)
print("Key1: " + str(simple_d["key1"]))
print()

# Single Dictionary
employee = {
    "employee_id": 12345678,
    "first_name": "Bob",
    "last_name": "Smith",
    "department": "Marketing",
    "age": 25,
    "hourly_rate": 23.50,
    "insurance": True
}
print(employee)
print("Employee Key: " + str(employee["employee_id"]))
print("Employee Age: " + str(employee.get("age")))
print()

# Nested Dictionary
employees = {
    "e1": {
        "employee_id": 23456789,
        "first_name": "Mateo",
        "last_name": "Garcia",
        "department": "CEO",
        "age": 53,
        "hourly_rate": 144.33,
        "insurance": True
    },
    "e2": {
        "employee_id": 34567890,
        "first_name": "Sally",
        "last_name": "Jones",
        "department": "IT",
        "age": 41,
        "hourly_rate": 36.00,
        "insurance": True
    }
}
print(employees)
print("Employee 1 ID: " + str(employees["e1"]["employee_id"]))
print("Employee 2 ID: " + str(employees["e2"]["employee_id"]))

Output:

Empty Dictionary: {}

Simple Dictionary: {'key1': 111111}
Key1: 111111

Employee Dictionary: {'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True}
Employee Key: 12345678

Employees Dictionary: {'e1': {'employee_id': 23456789, 'first_name': 'Mateo', 'last_name': 'Garcia', 'department': 'CEO', 'age': 53, 'hourly_rate': 144.33, 'insurance': True}, 'e2': {'employee_id': 34567890, 'first_name': 'Sally', 'last_name': 'Jones', 'department': 'IT', 'age': 41, 'hourly_rate': 36.0, 'insurance': True}}
Employee 1 ID: 23456789
Employee 2 ID: 34567890

Code & Output Details:

Updating (Changing) Dictionaries

Once we have created a dictionary, we can use several approaches we can use to update (change) existing values in the dictionary. We can update values directly based on existing keys or we can use the .update() method of the dictionary data structure to update values based on their keys as well. Here are some examples with sample Output and Code & Output Details below.

Examples:

employee = {
    "employee_id": 12345678,
    "first_name": "Bob",
    "last_name": "Smith",
    "department": "Marketing",
    "age": 25,
    "hourly_rate": 23.50,
    "insurance": True
}
print(employee)
employee["department"] = "Sales"
print(employee)
print("New Department: " + employee["department"])
employee.update({"hourly_rate": 29.00})
print(employee)
print("New Hourly Rate: " + str(employee["hourly_rate"]))

Output:

{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Sales', 'age': 25, 'hourly_rate': 23.5, 'insurance': True}
New Department: Sales
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Sales', 'age': 25, 'hourly_rate': 29.0, 'insurance': True}
New Hourly Rate: 29.0

Code & Output Details:

Adding Dictionary Items

We can also add new key:value pairs to a dictionary, which changes its size and again is possible because dictionaries are mutable (changeable). We can add pairs directly or use the dictionary data structure's update() method as demonstrated below:.

Examples:

employee = {
    "employee_id": 12345678,
    "first_name": "Bob",
    "last_name": "Smith",
    "department": "Marketing",
    "age": 25,
    "hourly_rate": 23.50,
    "insurance": True
}
print(employee)
employee["years_service"] = 14
print(employee)
employee["office_location"] = "Building 1"
print(employee)
employee.update({"work_schedule": "Day Shift"})
print(employee)

Output:

{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14, 'office_location': 'Building 1'}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14, 'office_location': 'Building 1', 'work_schedule': 'Day Shift'}

Code & Output Details:

Removing (Deleting) Dictionary Items

We can remove (delete) key:value pairs from a dictionary in several different ways, as demonstrated below:

Examples:

employee = {
    "employee_id": 12345678,
    "first_name": "Bob",
    "last_name": "Smith",
    "department": "Marketing",
    "age": 25,
    "hourly_rate": 23.50,
    "insurance": True
}
employee.pop("department")
print(employee)
employee.popitem()
print(employee)
del employee["age"]
print(employee)
employee.clear()
print(employee)
del employee
print(employee)

Output:

{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14, 'office_location': 'Building 1'}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14, 'office_location': 'Building 1', 'work_schedule': 'Day Shift'}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14, 'office_location': 'Building 1', 'work_schedule': 'Day Shift'}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14, 'office_location': 'Building 1'}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14, 'office_location': 'Building 1'}
{}
Traceback (most recent call last):
  File "C:\Users\jg\PycharmProjects\Computing1010\Lecture.py", line 28, in 
    print(employee)
NameError: name 'employee' is not defined

Code & Output Details:

Additional Dictionary Methods

The dictionary data structure has a few additional methods: fromkeys(), copy(), and setdefault().

Examples:

# Example of fromkeys() method:
# Creates a dictionary based on a list of keys,
# with an optional default value for each key
key_list = ["key1", "key2", "key3"]
default_value = 0
new_dictionary = dict.fromkeys(key_list, default_value)
print(new_dictionary)
print()

# We'll use this employee dictionary for the next
# two method examples...
employee = {
    "employee_id": 12345678,
    "first_name": "Bob",
    "last_name": "Smith",
    "department": "Marketing",
    "age": 25,
    "hourly_rate": 23.50,
    "insurance": True
}
print(employee)

# Example of copy() method:
# Copies a dictionary
copy_of_employee = employee.copy()
print(copy_of_employee)
print()

# Example of setdefault() method:
# Returns a value based on a specified key, if the
# key does not exist, the key is created and its
# value set to the specified value.
sal = employee.setdefault("hourly_rate", 0)
print(sal)
sal = employee.setdefault("annual_salary", 48880)
print(sal)
print(employee)

Output:

{'key1': 0, 'key2': 0, 'key3': 0}

{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True}

23.5
48880
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'annual_salary': 48880}

Code & Output Details:

Built-In Python Functions & Operators with Dictionaries

In addition to the Dictionary Methods  demonstrated above, there are several Python built-in functions we can use with dictionaries as well: len(), str() and type(). Also the in and == operators are useful with dictionaries as well.

Examples:

employee = {
    "employee_id": 12345678,
    "first_name": "Bob",
    "last_name": "Smith",
    "department": "Marketing",
    "age": 25,
    "hourly_rate": 23.50,
    "insurance": True
}
print("Length of employee dictionary: " + str(len(employee)))
print("Employee dictionary converted to string: " + str(employee))
print(type(employee))
if "department" in employee:
print("Department: " + employee["department"])
d1 = {1, 2, 3, 4, 5}
d2 = {1, 2, 3, 4, 5}
d3 = {5, 4, 3, 2, 1}
d4 = {1, 2, 3, 4, 5, 6}
d5 = {"A", "B", "C"}
print(d1 == d2)
print(d1 == d3)
print(d1 == d4)
print(d1 == d5)

Output:

Length of employee dictionary: 7
Employee dictionary converted to string: {'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True}

Department: Marketing
True
True
False
False

Code & Output Details:


Practice Problems

Problem 1

Write a Python program that creates a simple one-entry dictionary with a single key:value pair where the key is a customer ID and the value is an integer value like 1234. Then use a print statement to print the following:

Customer ID: 1234



Problem 2

Write a Python program that creates a multi-entry dictionary with a four key:value pairs of the following keys:

customer_id
first_name
last_name
email

You can include any data values for those four keys that you like. Then use a single print statement to print the values of the four dictionary entries. The output should look something like this:

--------------------
Customer
--------------------
Customer ID: 1234
Name: Bob Smith
Email: bob@abc.com
--------------------




Problem 3

Copy your code from Problem 2 above that will produce the same output, and then add code to change the value of the customer's email address. And then, duplicate your output code to display the before and after the email address value:

Note: We will see a more efficient way to repeat blocks of code in Chapter 3.




 





© 2023 John Gordon
Cascade Street Publishing, LLC