= {'jack': 4098, 'sape': 4139} tel
Techniques and patterns with dictionaries
Methods
From Python Documentation:
- Take a look at methods you may find useful and note them down. here. Try to “play around” with them later.
Constructors
- There are many ways to construct a dictionary.
= dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) tel
= dict(sape=4139, guido=4127, jack=4098) tel
- You can even use dictionary comprehensions. What will be the resulting dictionary in the following program?
= {name : {x: 0 for x in range(1990,2023)} for name in ['Ronaldo', 'Rivaldo', 'Neymar']} goals
Nesting dictionaries example: XML files
- The following code uses the
requests
module to download a XML file, and the ElementTree class to parse it into nested dictionaries. - The XML file was generated by the BoardGameGeek website and contains your professor’s board game collection. :D
import requests
import xml.etree.ElementTree as ET
# URL of the XML file
= "https://cs.calvin.edu/courses/cs/108/fsantos/units/08/activities/bgg_collection.xml"
url
# Send a GET request to the URL to retrieve the XML content
= requests.get(url)
response
# Check if the request was successful
if response.status_code == 200:
# Parse the XML content
= response.content
xml_content = ET.fromstring(xml_content)
root
= {}
collection # Process the XML data
for item in root:
= item.find('name').text # get the game name
gamename
= {}.copy() # construct the dictionary with the game's attributes
game = game
collection[gamename]
'year'] = item.find('yearpublished').text
game['stats'] = item.find('stats').attrib game[
- Note: XML is a very common data interchange format. Its main advantage is being application and language independent. You can check some basics here.
Looping through dictionaries
- Try to run the code in your machine and now write some code to loop through all the names and stats of the games. Make it a function!
- For example:
for game, value in collection.items():
print(game+': ')
for att, v in value.items():
print(att, v)
print()
- Try to remove some games from this dictionary collection using the
del
statement. You can even use a loop:
for game in ['Abstratus', 'Agricola', 'Whale Riders']:
del collection[game]