0% found this document useful (0 votes)
8 views

COMP 593 - Lecture 2 - Dictionaries and Data Structures

Uploaded by

urvishabhoi90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

COMP 593 - Lecture 2 - Dictionaries and Data Structures

Uploaded by

urvishabhoi90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

COMP 593

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"

• Written as a sequence of comma-separated key:value pairs between


curly braces

>>> ext = {'jesse': 1674, 'jeremy': 1134, 'mamdouh': 1688}


>>> info = {'name': 'Bob Loblaw', 'age': 45}

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)

• But there are some significant differences


• Dictionary values are accessed using keys instead of integers
• The key:value pairs in a dictionary are ordered in the sequence in which they are added
to the dictionary, but the ordering is mostly irrelevant

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

# Dictionary that maps city name to NHL team name


nhl_teams = {} Creates an empty dictionary
nhl_teams['Quebec'] = 'Nordiques'
nhl_teams['Montreal'] = 'Canadiens'
nhl_teams['Ottawa'] = 'Senators'
nhl_teams['Toronto'] = 'Maple Leafs'
nhl_teams['Winnipeg'] = 'Jets'
nhl_teams['Edmonton'] = 'Oilers'
nhl_teams['Calgary'] = 'Flames'
nhl_teams['Vancouver'] = 'Canucks'

8
Example: Accessing Dictionary Values
# Print the name of Calgary's team
print(f"The Calgary {nhl_teams['Calgary']}")

The Calgary Flames

# Change the name of Montreal's team to "Habs"


nhl_teams['Montreal'] = 'Habs'

# Quebec Nordiques become the Colorado Avalanche


del nhl_teams['Quebec']
nhl_teams['Colorado'] = 'Avalanche' Keys cannot be changed, so it is
necessary to delete the Quebec entry
and create a new key:value pair
9
Example: Accessing Dictionary Values
# Accessing non-existent key throws a KeyError exception
print(nhl_teams['Halifax'])
KeyError: 'Halifax'

# Check if key exists before accessing it


if 'Halifax' in nhl_teams:
print(nhl_teams['Halifax'])

# get() method returns default value if key does not exist


print(nhl_teams.get('Halifax', 'No Team'))

No Team
10
Example: Iterating Dictionary Keys
# Iterating dictionary keys
for city in nhl_teams:
print(f'The {city} {nhl_teams[city]}')

The Montreal Habs


The Ottawa Senators
The Toronto Maple Leafs
The Winnipeg Jets
The Edmonton Oilers
The Calgary Flames
The Vancouver Canucks
The Colorado Avalanche
11
Example: Iterating Dictionary Keys and Values
# Iterating dictionary keys and values
for city, name in nhl_teams.items():
print(f'The {city} {name}')
The items() method returns a
dict_items view object that can be
The Montreal Habs thought of as a list of tuples
The Ottawa Senators containing key:value pairs
The Toronto Maple Leafs
The Winnipeg Jets
The Edmonton Oilers
The Calgary Flames
The Vancouver Canucks
The Colorado Avalanche

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')

# Print both New York team names


print(f"The New York {nhl_teams['New York'][0]}")
print(f"The New York {nhl_teams['New York'][1]}")

The New York Rangers


The New York 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

• Finding values in a dictionary is faster than in a list


• Usually have to search through list to find what you are looking for

• Dictionaries can do things lists cannot


• e.g., Mapping city names to team names

• JSON-formatted data can be directly converted to a dictionary


• Dictionaries can be directly converted to JSON formatted data
• Data transmitted between computers is often in JSON format

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

• Often, a dictionary is used as the base data type


• Offers maximum flexibility and dynamic growth potential
• Other object types are nested inside the dictionary
• Nested data structures are accessed via descriptively named key

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

You might also like