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.
tel = {'jack': 4098, 'sape': 4139}
tel = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
tel = dict(sape=4139, guido=4127, jack=4098)
  • You can even use dictionary comprehensions. What will be the resulting dictionary in the following program?
goals = {name : {x: 0 for x in range(1990,2023)} for name in ['Ronaldo', 'Rivaldo', 'Neymar']}

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
url = "https://cs.calvin.edu/courses/cs/108/fsantos/units/08/activities/bgg_collection.xml"

# Send a GET request to the URL to retrieve the XML content
response = requests.get(url)

# Check if the request was successful
if response.status_code == 200:
    # Parse the XML content
    xml_content = response.content
    root = ET.fromstring(xml_content)

    collection = {}
    # Process the XML data
    for item in root:
      gamename = item.find('name').text # get the game name
    
      game = {}.copy() # construct the dictionary with the game's attributes
      collection[gamename] = game
    
      game['year'] = item.find('yearpublished').text
      game['stats'] = item.find('stats').attrib
  • 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]