1 of 54

Dictionaries

Jake Shoudy

Oct 14, 2022

CSCI 110 - Lecture 23

2 of 54

Announcements

3 of 54

Project 2: Part 1

Build a simple search engine using 1D lists :)

Two notes:

  • I’ve added some public tests to help
  • Use the “Terminal” to run your own tests

Due tonight at 11:59pm!

4 of 54

Project 2: Part 2

More search engine things using 2D Lists :)

Will be released tomorrow!

Due Sunday October 23rd at 11:59pm

5 of 54

HW8

Posted on Ed

Big O Practice and Coding problems using Sets

Due next Wednesday (Oct 19th)

6 of 54

Exam 2

Wednesday 10/26

Will cover all material through Dictionaries (today) but with a focus on material since midterm #1

7 of 54

Grading Rubrics

All grading rubrics available on class website

https://drive.google.com/corp/drive/folders/1mHYxvMOzYoVztKcIc0qOg9dFSmIfw1WO

8 of 54

Reminder: Feedback

9 of 54

Recap

10 of 54

Sets

An unordered, and unique collection of values.

Lookup times are fast!

Create a set via:

my_set = set() or

my_set = {‘a’, ‘b’, ‘c’}

11 of 54

Set Operators

Set operation

Runtime

s.add(item)

O(1)

s.remove(item)

O(1)

s.pop()

O(1)

in operator (ex: item in s)

O(1)

iteration (ex: for item in s)

O(n)

s1.union(s2) *

O(s + t) where s and t are the size of each set

s1.intersection(s2) *

O(min(s, t)) where s and t are the size of each set

s1.difference(s2) *

O(t) where t is the size of the second set

* operation does not mutate the set

12 of 54

Practice: Sets (adding and removing)

states = {‘WA’, ‘TN’, ‘OR’}

states.add(‘NC’)

len(states)

states.add(‘WA’)

states.remove(‘OR’)

states.remove(‘SC’)

states.pop()

{‘WA’, ‘TN’, ‘NC’, ‘OR’}

4

{‘WA’, ‘TN’, ‘NC’, ‘OR’}

{‘WA’, ‘TN’, ‘NC’}

KeyError

{‘WA’, ‘NC’} (removed a random one)

13 of 54

Practice: Sets (set math)

states_1 = {‘WA’, ‘NC’, ‘SC’, ‘OR’}

states_2 = {‘NC’, ‘TN’}

‘WA’ in states_1

states_1.union(states_2)

states_1.intersection(states_2)

states_1.difference(states_2)

states_2.difference(states_1)

True

{‘WA’, ‘TN’, ‘NC’, ‘SC’, ‘OR’}

{‘NC’}

{‘WA’, ‘SC’, ‘OR’}

{‘TN’}

14 of 54

Dictionaries

15 of 54

Intro to Dictionaries

Like physical dictionary, Python dictionaries are used for look-up

Physical dictionary: look up definitions for word

Programming dictionary: look up value using a key

16 of 54

Dictionaries

dictionary: ordered* collection of key:value pairs

Also known as map, because maps keys to values

prices = {'taco': 3.50, 'burrito': 8.00, 'enchilada': 6.99}

key

value

* ordered as of python 3.7 (2018) so be careful about your version. Maps are usually not ordered in most languages

17 of 54

Dictionaries

What?

unordered collection of key:value pairs

Why?

Useful for random access: accessing items out of order and key:value pairs

Lists are good for ordered data and for data without keys:value pairs

18 of 54

Syntax

cars = {

"Corolla": "Toyota",

"Accord": "Honda",

"Model 3": "Tesla",

"Prius": "Toyota"

}

Key

Value

19 of 54

Empty Dictionary

My_dictionary = dict() or…

my_dictionary = {}

Not a Set

empty_set = set()

20 of 54

Dictionaries, AKA...

Lookup tables

Maps

Hashmaps

Hash tables

21 of 54

Valid Types

What types can be in a dictionary?

  • Keys must be immutable.
    • From the types we know so far, ints, floats, booleans, and strings are all ok to be keys.
    • A list, set, or dictionary cannot be a key in a dictionary.
  • Values can be anything, mutable or immutable.

movie_info = {

'title': 'Your Name',

'year': 2016,

'rating': 'PG',

'running_time': 112,

'actors': ['Ryunosuke Kamiki', 'Mone Kamishiraishi'],

'score': 96,

}

22 of 54

Dictionary operations

23 of 54

Indexing O(1)

cars = {

"Corolla": "Toyota",

"Accord": "Honda",

"Model 3": "Tesla",

"Prius": "Toyota"

}

Index into dictionary using keys

cars["Corolla"]

cars["Accord"]

cars["Model 3"]

cars["Prius"]

"Toyota"

"Honda"

"Tesla"

"Toyota"

24 of 54

Indexing O(1)

cars = {

"Corolla": "Toyota",

"Accord": "Honda",

"Model 3": "Tesla",

"Prius": "Toyota"

}

Index into dictionary using keys

cars["Corolla"]

cars["Accord"]

cars["Model 3"]

cars["Prius"]

cars["Rav4"]

"Toyota"

"Honda"

"Tesla"

"Toyota"

25 of 54

KeyError

cars = {

"Corolla": "Toyota",

"Accord": "Honda",

"Model 3": "Tesla",

"Prius": "Toyota"

}

Index into dictionary using keys

cars["Corolla"]

cars["Accord"]

cars["Model 3"]

cars["Prius"]

cars["Rav4"]

"Toyota"

"Honda"

"Tesla"

"Toyota"

Traceback (most recent call last):

File "<stdin>", line 5, in <module>

KeyError: 'Rav4'

26 of 54

Use in operator to check keys

cars = {

"Corolla": "Toyota",

"Accord": "Honda",

"Model 3": "Tesla",

"Prius": "Toyota"

}

Index into dictionary using keys

cars["Corolla"]

cars["Accord"]

cars["Model 3"]

cars["Prius"]

"Toyota"

"Honda"

"Tesla"

"Toyota"

in operator only checks keys of the dictionary.

if "Rav4" in cars:

print(cars["Rav4"])

27 of 54

in operator O(1)

To check whether a key exists, use in operator

in operator only checks keys of dictionary

On average runs in O(1) (constant time!)

if 'Rav4' in cars:

print(cars['Rav4'])

else:

print('who made the Rav4?')

28 of 54

Mutation: Add an item O(1)

Insert new key:value pairs by assigning to new keys

On average runs in O(1) (constant time!)

cars = {

"Corolla": "Toyota",

"Accord": "Honda",

"Model 3": "Tesla",

"Prius": "Toyota"

}

cars['Rav4'] = 'Toyota'

29 of 54

Mutation: Add an item O(1)

Insert new key:value pairs by assigning to new keys

On average runs in O(1) (constant time!)

cars = {

"Corolla": "Toyota",

"Accord": "Honda",

"Model 3": "Tesla",

"Prius": "Toyota",

"Rav4": "Toyota"

}

cars['Rav4'] = 'Toyota'

30 of 54

Mutation: Change an item O(1)

Keys are unique, so assigning to an existing one replaces it

On average runs in O(1) (constant time!)

cars = {

"Corolla": "Toyota",

"Accord": "Honda",

"Model 3": "Tesla",

"Prius": "Toyota",

"Rav4": "Toyota"

}

cars['Corolla'] = 'Ferrari'

31 of 54

Mutation: Change an item O(1)

cars = {

"Corolla": "Ferrari",

"Accord": "Honda",

"Model 3": "Tesla",

"Prius": "Toyota",

"Rav4": "Toyota"

}

Keys are unique, so assigning to an existing one replaces it

On average runs in O(1) (constant time!)

cars['Corolla'] = 'Ferrari'

32 of 54

Mutation: Delete an item O(1)

Delete key:value pairs by passing the key to pop()

On average runs in O(1) (constant time!)

cars = {

"Corolla": "Ferrari",

"Accord": "Honda",

"Model 3": "Tesla",

"Prius": "Toyota",

"Rav4": "Toyota"

}

cars.pop('Model 3')

33 of 54

Mutation: Delete an item O(1)

Delete key:value pairs by passing the key to pop()

On average runs in O(1) (constant time!)

cars = {

"Corolla": "Ferrari",

"Accord": "Honda",

"Model 3": "Tesla",

"Prius": "Toyota",

"Rav4": "Toyota"

}

cars.pop('Model 3')

34 of 54

Iteration O(n)

Remember, dictionaries are ordered

Can iterate with for loop. Runs in O(n)

for key in dictionary:

print(key) # print current key

print(dictionary[key]) # print value at that key

Iterates over keys of dictionary

Keys are ordered in the same order that they were added

35 of 54

Ordered Dictionaries?

New versions of Python are released every so often!

Currently on 3.10

As of 3.7 (2018), dictionaries in python are ordered in the same order that they were added to the dictionary

In python, you may depend on the order of a dictionary but be careful about doing this in other languages (or if you are using an older version of python)

36 of 54

Iteration: Example

abbreviations = {'Louisiana': 'LA', 'Utah': 'UT', 'Oregon': 'OR'}

for state in abbreviations:

print('State: ', state)

print('Postal abbreviation: ', abbreviations[state])

37 of 54

Tracing Dictionary Iteration

abbreviations = {

'Louisiana': 'LA',

'Utah': 'UT',

'Oregon': 'OR'

}

for state in abbreviations:

print('State: ', state)

print('Postal abbreviation: ', abbreviations[state])

state

38 of 54

Tracing Dictionary Iteration

abbreviations = {

'Louisiana': 'LA',

'Utah': 'UT',

'Oregon': 'OR'

}

for state in abbreviations:

print('State: ', state)

print('Postal abbreviation: ', abbreviations[state])

'Louisiana'

state

39 of 54

Tracing Dictionary Iteration

abbreviations = {

'Louisiana': 'LA',

'Utah': 'UT',

'Oregon': 'OR'

}

for state in abbreviations:

print('State: ', state)

print('Postal abbreviation: ', abbreviations[state])

State: Louisiana

'Louisiana'

state

40 of 54

Tracing Dictionary Iteration

abbreviations = {

'Louisiana': 'LA',

'Utah': 'UT',

'Oregon': 'OR'

}

for state in abbreviations:

print('State: ', state)

print('Postal abbreviation: ', abbreviations[state])

State: Louisiana

Postal abbreviation: LA

'Louisiana'

state

41 of 54

Tracing Dictionary Iteration

abbreviations = {

'Louisiana': 'LA',

'Utah': 'UT',

'Oregon': 'OR'

}

for state in abbreviations:

print('State: ', state)

print('Postal abbreviation: ', abbreviations[state])

'Utah'

state

State: Louisiana

Postal abbreviation: LA

42 of 54

Tracing Dictionary Iteration

abbreviations = {

'Louisiana': 'LA',

'Utah': 'UT',

'Oregon': 'OR'

}

for state in abbreviations:

print('State: ', state)

print('Postal abbreviation: ', abbreviations[state])

State: Louisiana

Postal abbreviation: LA

State: Utah

'Utah'

state

43 of 54

Tracing Dictionary Iteration

abbreviations = {

'Louisiana': 'LA',

'Utah': 'UT',

'Oregon': 'OR'

}

for state in abbreviations:

print('State: ', state)

print('Postal abbreviation: ', abbreviations[state])

State: Louisiana

Postal abbreviation: LA

State: Utah

Postal abbreviation: UT

'Utah'

state

44 of 54

Tracing Dictionary Iteration

abbreviations = {

'Louisiana': 'LA',

'Utah': 'UT',

'Oregon': 'OR'

}

for state in abbreviations:

print('State: ', state)

print('Postal abbreviation: ', abbreviations[state])

State: Louisiana

Postal abbreviation: LA

State: Utah

Postal abbreviation: UT

'Oregon'

state

45 of 54

Tracing Dictionary Iteration

abbreviations = {

'Louisiana': 'LA',

'Utah': 'UT',

'Oregon': 'OR'

}

for state in abbreviations:

print('State: ', state)

print('Postal abbreviation: ', abbreviations[state])

State: Louisiana

Postal abbreviation: LA

State: Utah

Postal abbreviation: UT

State: Oregon

'Oregon'

state

46 of 54

Tracing Dictionary Iteration

abbreviations = {

'Louisiana': 'LA',

'Utah': 'UT',

'Oregon': 'OR'

}

for state in abbreviations:

print('State: ', state)

print('Postal abbreviation: ', abbreviations[state])

'Oregon': 'OR'

state

State: Louisiana

Postal abbreviation: LA

State: Utah

Postal abbreviation: UT

State: Oregon

Postal abbreviation: OR

47 of 54

Iterate Over Keys

abbreviations = {

'Louisiana': 'LA',

'Utah': 'UT',

'Oregon': 'OR'

}

for state in abbreviations:

print('State: ', state)

print('Postal abbreviation: ', abbreviations[state])

State: Louisiana

Postal abbreviation: LA

State: Utah

Postal abbreviation: UT

State: Oregon

Postal abbreviation: OR

48 of 54

Iterate Over Values

abbreviations = {

'Louisiana': 'LA',

'Utah': 'UT',

'Oregon': 'OR'

}

for abbreviation in abbreviations.values():

print('Postal abbreviation: ', abbreviation)

Postal abbreviation: LA

Postal abbreviation: UT

Postal abbreviation: OR

49 of 54

Iterate Over Key, Value

abbreviations = {

'Louisiana': 'LA',

'Utah': 'UT',

'Oregon': 'OR'

}

for state, abbreviation in abbreviations.items():

print('State: ', state)

print('Postal abbreviation: ', abbreviation)

State: Louisiana

Postal abbreviation: LA

State: Utah

Postal abbreviation: UT

State: Oregon

Postal abbreviation: OR

50 of 54

Accumulation

Dictionaries are often used for accumulation

Keep running count of information

Example:

How many of which letter is used in a sentence? That is, how many times is the letter 'a' used in a sentence? What about 'b'? 'c'? 'd'? 'e'? …?

51 of 54

Accumulation: Letter Count

sentence = 'Hello how are you today'

letter_count = {}

for letter in sentence:

if letter in letter_count:

letter_count[letter] = letter_count[letter] + 1

else:

letter_count[letter] = 1

print(letter_count)

52 of 54

Let’s Code!

53 of 54

Dictionaries

What?

ordered* collection of key:value pairs

Can add, change, delete items from dictionary

Can iterate over dictionary, use accumulator pattern to keep running count

Why?

Useful for random access: accessing items out of order and key:value pairs

Lists are better for ordered data and for data without keys:value pairs

54 of 54

Questions?