Dictionaries

Overview

Teaching: 10 min
Exercises: 5 min
Questions
  • How can I represent more complex datasets?

Objectives
  • Use a dictionary to represent complex, nested datasets

  • Retrieve data from a dictionary at any level of its hierarchy

A dictionary stores many values in a single structure, and each value has a ‘key’.

metadata = { 'title' : 'Guards! Guards!', 'author' : 'Terry Pratchett'}
print('metadata:', metadata)
print('title:', metadata['title'])
metadata: {'title': 'Guards! Guards!', 'author': 'Terry Pratchett'}
title: Guards! Guards!

New dictionaries can be created by with the dict() constructor function and a sequence of key-value pairs.

publisher = dict(name='HarperTorch', place='New York', year=2001)
print('publisher:', publisher)
publisher: {'name': 'HarperTorch', 'place': 'New York', 'year': 2001}

Add or replace items in a dictionary by accessing them by key. Dictionaries can store any type of item, even lists or other dictionaries.

metadata = { 'title' : 'Guards! Guards!', 'author' : 'Terry Pratchett' }
metadata['publisher'] = publisher
metadata['format'] = 'Print book'
metadata['subjects'] = [ 'crime', 'mystery', 'plots', 'dragons', 'dwarves']
print('metadata:', metadata)
metadata: {'title': 'Guards! Guards!', 'author': 'Terry Pratchett', 'publisher': {'name': 'HarperTorch', 'place': 'New York', 'year': 2001}, 'format': 'Print book', 'subjects': ['crime', 'mystery', 'plots', 'dragons', 'dwarves']}

Use multiple key selectors in a row to get at nested dictionaries and lists

print('place of publication: ', metadata['publisher']['place'])
print('second subject: ', metadata['subjects'][1])
place of publication:  New York
second subject:  mystery

You have been told you need at least 7 subjects in your metadata for this book.

How many subjects do you have now? Add a few more.

Solution

print(len(metadata['subjects'])) metadata['subjects'].extend(['swords', 'royalty']) print('metadata: ', metadata)

You’re actually looking for the original UK edition, update the publisher info accordingly

Change the publication date to 1998. Change the publisher to ‘Corgi’ Change the publication place to ‘London’

Solution

metadata['publisher'] = dict(name='Corgi', place='London', year=1998) print('metadata: ', metadata)

Key Points

  • Every item in a dictionary has its own unique key

  • Dictionaries can hold any kind of item, including lists and other dictionaries

  • Data in a dictionary can be accessed by referencing its keys