COMP 593 - Lecture 2 - Dictionaries and Data Structures
COMP 593 - Lecture 2 - Dictionaries and Data Structures
Scripting Applications
Lecture 2:
Dictionaries and Data Structures
Objectives
• Explain what a dictionary is and how it can be used in a
Python script
• Write code that performs basic actions on a dictionary:
initialize, add, remove, and modify key:value pairs
• Combine dictionaries, lists, and other objects to create a
complex data structure
• Iterate a dictionary or an iterable nested in a dictionary
• Design a complex data structure that holds related
information
2
Dictionaries
Dictionaries
• A dictionary is a data type that holds a collection of key:value pairs
• Keys can be any type of immutable object, but are usually strings
• Values can be any type of object
• Sometimes called "associative array", "hash", or "hash table"
https://docs.python.org/3/tutorial/datastructures.html#dictionaries
4
Dictionaries vs Lists
• Dictionaries are similar to lists
• Both can hold multiple values of any type
• Both are mutable objects (i.e., they can be modified)
5
Example: Comma-Separated Key:Value Pairs
# Dictionary that maps city name to NHL team name
nhl_teams = {
'Quebec': 'Nordiques',
'Montreal': 'Canadiens',
'Ottawa': 'Senators',
'Toronto': 'Maple Leafs',
'Winnipeg': 'Jets',
'Edmonton': 'Oilers',
'Calgary': 'Flames',
'Vancouver': 'Canucks'
}
Keys Values
https://realpython.com/python-dicts/#defining-a-dictionary
6
Example: Using the dict() constructor
# Dictionary that maps city name to NHL team name
nhl_teams = dict(
Quebec = 'Nordiques',
Montreal = 'Canadiens',
Ottawa = 'Senators',
Toronto = 'Maple Leafs',
Winnipeg = 'Jets',
Edmonton = 'Oilers',
Calgary = 'Flames',
Vancouver = 'Canucks' There are also various other
) ways the dict() constructor can
be used to create a dictionary
https://docs.python.org/3/library/functions.html#func-dict
7
Example: Adding Key:Value Pairs to a Dictionary
8
Example: Accessing Dictionary Values
# Print the name of Calgary's team
print(f"The Calgary {nhl_teams['Calgary']}")
No Team
10
Example: Iterating Dictionary Keys
# Iterating dictionary keys
for city in nhl_teams:
print(f'The {city} {nhl_teams[city]}')
https://realpython.com/python-dicts/#built-in-dictionary-methods
12
Example: Dictionary Values Can Be Any Type
# Add both New York team names as a tuple
nhl_teams['New York'] = ('Rangers', 'Islanders')
https://realpython.com/python-dicts/#built-in-dictionary-methods
13
Why Would I Use A Dictionary?
• Sometimes convenient to access items using a descriptive key name
• Rather than a meaningless integer list index, assuming your data is not ordered
https://favtutor.com/blogs/list-vs-dictionary
14
Complex Data Structures
Complex Data Structures
• Dictionaries, lists, and tuples can be combined to create complex
data structures, e.g.,
• List of dictionaries
• Dictionary value can be a list
• Dictionary value can be a list of dictionaries
16
Name
Skin
Loadout
Health & Shield
17
Base structure
player = { is a dictionary
print(player['name'])
'name': 'Sweaty McBot',
'health': 100,
Sweaty McBot
'shield': 100,
'skin': {
'name': 'Doggo', Nested dictionary
'style': 'Militia'
}, print(player['skin']['name'])
'loadout': [
{
Doggo
'name': 'Assault Rifle',
'rarity': 'Rare',
'ammo': 130 List of
}, dictionaries
{
'name': 'Machine SMG',
'rarity': 'Common', print(player['loadout'][1]['name'])
'ammo': 214
} Machine SMG
]
}
Indentation is not necessary, but helps to visualize the hierarchy of the complex data structure.
https://fortnite.fandom.com/wiki/Doggo
18
player = {
'name': 'Sweaty McBot',
'health': 100,
'shield': 100, # Print all items in loadout list
'skin': { for item in player['loadout']:
'name': 'Doggo', print(item['rarity'], item['name'])
'style': 'Militia'
}, Rare Assault Rifle
'loadout': [ Common Machine SMG
{
'name': 'Assault Rifle',
'rarity': 'Rare',
'ammo': 130 # Print all values in skin dictionary
}, for value in player['skin'].values():
{ print(value)
'name': 'Machine SMG',
'rarity': 'Common', Doggo
'ammo': 214 Militia
}
]
}
19
player = {
'name': 'Sweaty McBot',
# Reduce shield by 80
'health': 100,
player['shield'] -= 80
'shield': 100,
'skin': {
# Change skin style to 'Default'
'name': 'Doggo',
player['skin']['style'] = 'Default'
'style': 'Militia'
},
# Remove Machine SMG from loadout
'loadout': [
player['loadout'].pop(1)
{
'name': 'Assault Rifle',
'rarity': 'Rare',
'ammo': 130 # Add new item to loadout
}, new_item = {
{ 'name': 'Drum Shotgun',
'name': 'Machine SMG', 'rarity': 'Epic',
'rarity': 'Common', 'ammo': 12
'ammo': 214 }
} player['loadout'].append(new_item)
]
}
20