1 of 23

A more sophisticated data structure.

Data 94, Spring 2021 @ UC Berkeley

Suraj Rampure, with help from many others

Dictionaries

13

2 of 23

Overview

Announcements

  • Motivating dictionaries.
  • Syntax for creation and access.
  • Modifying dictionaries.
  • Iteration.
  • Example: area codes.
    • Video posted on Ed for it, won’t cover in class.
  • Homework 3 + Survey 3 due Wednesday.
  • Quiz 1 and Homework 2 grades released, see Ed.
  • Moved Quiz 2 and 3 dates around slightly: see course website.
    • Now, all quizzes are on a Friday.
  • Look at the readings!

3 of 23

Motivation

4 of 23

Lists

A list is an ordered collection of values. Each element of a list has a position, called its index.

names = ['bill', 'sarah', 'cal', 'nina', 'joe']

The only way to access an element of a list is by using its position.

names[1]

5 of 23

Dictionaries (in real life)

How do you use a (real) dictionary?

  1. Pick a word.
  2. Find that word in the dictionary.
  3. Read its definition.

Dictionaries store a “mapping” between words and definitions.

6 of 23

Dictionaries (in Python)

Dictionaries in Python store key-value pairs.

{'name': 'Junior', 'age': 11, 4: ['kibble', 'treat']}

  • A key is what we use to look up values.
    • Can be numbers or strings.
  • A value can be anything!
    • Numbers, strings, lists, or even other dictionaries!
  • In a list, each value has a position; in a dictionary, each value has a key.
  • Real-life analogy: keys are words, values are definitions.

7 of 23

Dictionary syntax

  • {curly brackets} denote the start and end of a dictionary.
  • A colon is used to specify a single key-value pair.

'age': 11

key

value

  • A comma is used to separate key-value pairs.
  • Dictionaries are often written with one key-value pair per line to help with readability.

dog = {'name': 'Junior',

'age': 11,

4: ['kibble', 'treat']}

8 of 23

Access

In order to retrieve an element from a dictionary, we use its key.

dict_name[key]

The dog dictionary only has three valid keys: 'name', 'age', and 4. Attempting to index using anything else will cause a KeyError.

Dictionary elements don’t have positions!*

9 of 23

Quick Check 1

After defining bears, what are the values of:

  • bears['polar']['hungry']
  • bears[None][1]
  • bears['weight_range']

10 of 23

Modification

11 of 23

Creating dictionaries and adding elements

We create an empty dictionary similar to how we create an empty list – but with curly brackets.

To add new key-value pairs to a dictionary, we write

dict_name[key] = value

12 of 23

Keys must be unique

Keys in a dictionary are unique. If a key already exists and you assign it a new value, it replaces the existing value.

Multiple keys can have the same value, though.

We can also modify values, like so.

13 of 23

Quick Check 2

After running the following four lines of code, what are the values of numbers['1'], numbers['five'], numbers[1], and numbers[2]?

two = 1

numbers = {'1': 2}

numbers['five'] = 5

numbers[two] = numbers['1']

numbers[2] = numbers[1] + numbers['five']

14 of 23

Iteration

15 of 23

Dictionaries 🤝 lists

Lists and dictionaries are both collections, which are types in Python that are used to store multiple values.

We can easily:

  • Get the length.
  • Get the keys and values as a list.
  • Check to see if a key is present.

Displays keys in the order they were added.

16 of 23

Iteration

We often iterate through all keys in a dictionary.

Prints all values.

Prints all keys and values.

17 of 23

Example: replace slang

For every abbreviation, check to see if it’s in the message.

If it is, replace it with its full form.

�Return the updated message.

18 of 23

Example: area codes

Video posted on Ed!

19 of 23

Area codes

Suppose we have a dictionary codes_dict where each key is an area code and each value is the state corresponding to that code.

codes_dict = {...

208: 'Idaho',

209: 'California',

210: 'Texas',

212: 'New York',

213: 'California',

...}

Our goal is to create a new dictionary states_dict where each key is a state and each value is a list of area codes in that state.

states_dict = {...

'Washington': [206, 253, ...],

'Maine': [207],

'Idaho': [208],

'California': [209, 213, ...],

'Texas': [210, 214, ...],

...}

our job

20 of 23

Idea:

For each area code (key)…

  1. Get the corresponding state.
  2. If we’ve seen the state already, add the area code to that state’s list.
  3. If we haven’t seen the state already (i.e. it is the first time we’re encountering this state in our loop), make a list for this state and add this area code to it.

states_dict = {}

for code in codes_dict.keys():

state = codes_dict[code]

if state in states_dict:

states_dict[state].append(code)

else:

states_dict[state] = [code]

codes_dict = {...

208: 'Idaho', 209: 'California',

210: 'Texas', 212: 'New York',

213: 'California', ...}

21 of 23

Summary, next time

22 of 23

Summary

  • Dictionaries are used to store key-value pairs.
    • In a list, each value has a position; in a dictionary, each value has a key.
    • Real-life analogy: keys are words, values are definitions.
  • We can easily:
    • Create an empty dictionary or a dictionary with some values in it.
    • Add and modify key-value pairs.
    • Check to see if keys are present.
    • Iterate over all keys or values.

A data structure is a way to organize and store data.

Lists and dictionaries are both data structures!

23 of 23

Next time

Announcements

  • How is data stored on a computer?
    • Spreadsheets.
    • CSV files.
    • JSON files.
  • How do we access data stored in a file using a Jupyter notebook?
  • What is a module, and how do we use modules?
  • Homework 3 + Survey 3 due Wednesday.
  • Quiz 1 and Homework 2 grades released, see Ed.
  • Moved Quiz 2 and 3 dates around slightly: see course website.
    • Now, all quizzes are on a Friday.
  • Look at the readings!