Python's Data Structures: Dictionary
CSCI 1470
by K. Yue
1. Dictionary Review
2. Dictionary Basics
Example:
#
# Python dict basic
#
person_1 = {
"name": "Jane",
"dob": "12/08/1997",
"city": "Houston"
}
print(f"person_1: {person_1}")
print(f"id(person_1): {id(person_1)}")
person_1['school'] = 'uhcl'
print(f"person_1 after 'person_1['school'] = 'uhcl'': {person_1}")
print("dicts are mutable.")
print(f"id(person_1): {id(person_1)}")
print("""
# keys are unique.
person_2 = {
"name": "Jane",
"name": "Johnson",
"dob": "12/08/1997",
"city": "Houston"
}
""")
# keys are unique.
person_2 = {
"name": "Jane",
"name": "Johnson",
"dob": "12/08/1997",
"city": "Houston"
}
print(f"person_2: {person_2}")
def hello():
print("hello")
def bye():
print("bye")
print("""
# keys can be any mutable.
dict_1 = {
hello: 1,
bye: 2,
"hello": 3,
4: 4
}
""")
# keys can be any immutable.
dict_1 = {
hello: 1,
bye: 2,
"hello": 3,
4: 4
}
print(f"dict_1: {dict_1}")
print(f"dict_1[hello]: {dict_1[hello]}")
print(f"dict_1['hello']: {dict_1['hello']}")
print(f"dict_1[4]: {dict_1[4]}")
# Keys cannot be mutable.
print("""
# Keys cannot be mutable.
list_1 = [1,2,3]
dict_2 = {
"hey": 1,
list_1: 2
}
Traceback (most recent call last):
File "...", line 63, in <module>
dict_2 = {
TypeError: unhashable type: 'list'
""")
print("""
# values can be mutable.
list_1 = [1,2,3]
dict_2 = {
"hey": 1,
"ho": list_1
}
""")
# values can be mutable.
list_1 = [1,2,3]
dict_2 = {
"hey": 1,
"ho": list_1
}
print(f"list_1: {list_1}")
print(f"dict_2: {dict_2}")
#
list_1.append(4)
print("After 'list.append(4)':")
print(f" list_1: {list_1}")
print(f" dict_2: {dict_2}")
dict_2['ho'].append(7)
print("After 'dict_2['ho'].append(7):")
print(f" list_1: {list_1}")
print(f" dict_2: {dict_2}")
3. Modifying dicts
Example:
#
# Python dict: more.
#
person_1 = {
"name": "Jane",
"dob": "12/08/1997",
"city": "Houston"
}
print(f"person_1: {person_1}")
person_1['city'] = 'Galveston';
print(f"person_1 after 'person_1['city'] = 'Galveston'': {person_1}")
print(f"person_1['city']: {person_1['city']}")
print("""
print(f"person_1['state']: {person_1['state']}")
Traceback (most recent call last):
File "...\dict_more_1.py", line 16, in <module>
print(f"person_1['state']: {person_1['state']}")
KeyError: 'state'
""")
print("Use the error-safe method get(), which returns a user-specified value if the key cannot be found.")
print(f"person_1.get('city', 'unknown'): {person_1.get('city', 'unknown')}")
print(f"person_1.get('state', 'unknown'): {person_1.get('state', 'unknown')}")
print()
print("Replacing the name key by first and last name.")
del person_1['name']
print("del person_1['name']")
print(f"person_1 : {person_1}")
print("""
person_1['first name'] = 'Jane'
person_1['last name'] = 'Johnson'
""")
person_1['first name'] = 'Jane'
person_1['last name'] = 'Johnson'
print(f"person_1: {person_1}")
print(f"len(person_1): {len(person_1)}")
uhcl = {
'University abbreviation': 'uhcl',
'University name': 'University of Houston-Clear Lake',
'Univesrity state': 'Texas'
}
print(f"uhcl: {uhcl}")
print(f"person_1: {person_1}")
person_1.update(uhcl)
print(f"uhcl: {uhcl}")
print(f"person_1: {person_1}")
4. Iterating dicts
Example:
#
# Python dict: iteration
#
person_1 = {
'name': 'Jane',
'dob': '12/08/1997',
'city': 'Houston',
'university': 'UHCL'
}
print("""dict methods for iteration.
dict_1.keys(): Returns a view object of all keys.
dict_1.values(): Returns a view object of all values.
dict_1.items(): Returns a view object of all key-value pairs.
""")
print(f"person_1: {person_1}")
print(f"person_1.keys(): {person_1.keys()}")
print(f"person_1.values(): {person_1.values()}")
print(f"person_1.items(): {person_1.items()}")
print("""view objects are dynamic and live.
They are views/windows on the underlying dict.
""")
print("keys = person_1.keys()")
keys = person_1.keys()
print(f"keys: {keys}")
print("person_1['hobbies'] = {'primary': 'music', 'others': ['games', 'woodwork']}")
person_1['hobbies'] = {'primary': 'music', 'others': ['games', 'woodwork']}
print(f"person_1: {person_1}")
print(f"keys: {keys}")
# iterations to pretty print a dict.
print()
print(f"person_1: {person_1}")
print("""
print('{')
for key in person_1.keys():
print(f" {key}: {person_1[key]}")
print('}')
""")
print('{')
for key in person_1.keys():
print(f" {key}: {person_1[key]}")
print('}')
print("""
print('{')
for key, value in person_1.items():
print(f" {key}: {value}")
print('}')
""")
print('{')
for key, value in person_1.items():
print(f" {key}: {value}")
print('}')
print("""
import pprint
pprint.pp(person_1, indent=4)
""")
import pprint
pprint.pp(person_1, indent=4)
print()
print("pprint.pp(person_1, indent=4, sort_dicts=True)")
pprint.pp(person_1, indent=4, sort_dicts=True)
print("""
# simple summing use cases.
sales_by_region = {
'North': 1120,
'South': 2100,
'East': 3219,
'West': 4050}
total_sales = 0
for sales_amount in sales_by_region.values():
total_sales += sales_amount
print(f"Total sales across all regions: {total_sales}")""")
# simple summing use cases.
sales_by_region = {
'North': 1120,
'South': 2100,
'East': 3219,
'West': 4050}
total_sales = 0
for sales_amount in sales_by_region.values():
total_sales += sales_amount
print(f"Total sales across all regions: {total_sales}")
# version #2:
print('print(f"Total sales across all regions: {sum(sales_by_region.values())}")')
print(f"Total sales across all regions: {sum(sales_by_region.values())}")
5. Nested Data Structures (dict)
Example:
#
# Nested data structures.
#
# Each item in score_1 contains the scores of three homework assignments.
scores_1 = [
[96, 89, 97],
[88, 84, 83],
[64, 57, 72]
]
print("""
# Each item in score_1 is the score of three homework assignments.
scores_1 = [
[96, 89, 97],
[88, 84, 83],
[64, 57, 72]
]
""")
# print the individual scores of each student.
for item in scores_1:
print(f"student score: ", end="")
for score in item:
print(score, end=" ")
print()
print()
# putting a comma between scores.
for item in scores_1:
print(f"student scores: ", end="")
for pos, score in enumerate(item):
if pos == len(item)-1:
print(score)
else:
print(f"{score}, ", end="")
print()
# Second version using list comprehensions.
for item in scores_1:
print(f"student scores: ", end="")
str_item = [str(score) for score in item]
print(", ".join(str_item))
print()
# add student #
for student_num, item in enumerate(scores_1):
print(f"student #{student_num + 1} scores: ", end="")
for pos, score in enumerate(item):
if pos == len(item)-1:
print(score)
else:
print(f"{score}, ", end="")
# Each item in score_2 contains a dict with the name of the student as the key and the scores of three homework assignments as the value.
scores_2 = {
"Joe": [96, 89, 97],
"Jane": [88, 84, 83],
"Jenny": [64, 57, 72]
}
print()
for student in scores_2.keys():
print(f"{student}'s scores: ", end="")
for pos, score in enumerate(scores_2[student]):
if pos == len(item)-1:
print(score)
else:
print(f"{score}, ", end="")
scores_3 = {
"Joe": {"HW1": 96, "HW2": 89, "HW3": 97, "HW4": 84},
"Jane": {"HW1": 88, "HW2": 84, "HW3": 83},
"Jenny": {"HW1": 64, "HW2": 57, "HW4": 72}
}
print()
for student in scores_3.keys():
print(f"{student}'s scores: ", end="")
for pos, assignment_name in enumerate(scores_3[student].keys()):
if pos == len(scores_3[student].keys())-1:
print(f"{assignment_name}: {scores_3[student][assignment_name]}")
else:
print(f"{assignment_name}: {scores_3[student][assignment_name]}, ", end="")