1 of 19

CSE 160 Section 5

File I/O and Dictionaries!

CSE 160: Section 5

2 of 19

Logistics

  • Written check-in 5 due Friday Feb 6
  • Programming practice 5 due Wed Feb 11
  • HW3 due Feb 12
    • Submitting on Gradescope
    • Wait for autograder!
  • Resubmission Cycle 2/2 - 2/6
    • Don’t forget to fill out the resubmission form!

CSE 160: Section 5

3 of 19

Lecture Review: File I/O

CSE 160: Section 5

4 of 19

File I/O

my_file = open(filepath)

for line_of_text in my_file:

# process line_of_text

my_file.close()

CSE 160: Section 5

5 of 19

Split

  • Split can be a really helpful function when dealing with strings (which is what you’re processing in file i/o)

Example:

O

Output:

line_of_text = “you’re going to be amazing”

x = line_of_text.split()

print(x)

[“you’re”, “going”, “to”, “be”, “amazing”]

CSE 160: Section 5

6 of 19

Split

  • If you give split an argument, it will split the line of text on that. If you don’t give it anything, it will by default split on spaces.

Example:

O

Output:

line_of_text = “you’re,going,to,be,amazing”

x = line_of_text.split(“,”)

print(x)

[“you’re”, “going”, “to”, “be”, “amazing”]

CSE 160: Section 5

7 of 19

Lecture Review: Dictionary

CSE 160: Section 5

8 of 19

Dictionary

Collection of key-value pairs

  • Key type must be immutable and keys must be unique

  • Key-value pair order doesn’t matter (dictionaries are unordered)

  • Access value from a key using index syntax (square brackets)

  • If you try to access a key not that doesn’t exist in the dictionary, it will throw an error

CSE 160: Section 5

9 of 19

Dictionary

heights = {"Ella": 68,

"Martin": 72,

"Lilly": 49,

"William": 50,

"Simon": 70}

print(heights["Lilly"]) # 49

print(heights["Wen"]) # KeyError

heights["Wen"] = 63 # Add a key-value pair

heights["Lilly"] = 50 # Update value

print(heights["Lilly"]) # 50

CSE 160: Section 5

10 of 19

Dictionary

# print out all keys

for key in heights.keys():

print(key)

# print out all values

for value in heights.values():

print(value)

# print out keys and values

for (key, value) in heights.items():

print(key, value)

# another method

for key in heights:

value = heights[key]

print(key, value)

CSE 160: Section 5

11 of 19

Dictionary built-in functions

Operation (dictionary d)

Description

d.items()

Returns a list containing a tuple for each key-value pair.

d.keys()

Returns a list of the dictionary keys.

d.values()

Returns a list of all values in the dictionary.

d.pop(key)

Removes the element with the specified key.

d.popitem()

Removes the last inserted key-value pair.

d.update(dict)

Updates the dictionary with the specified key-value pairs.

d.copy()

Returns a copy of the dictionary.

d.get(key)

Returns the value of the given key.

CSE 160: Section 5

12 of 19

Additional Operations

  • Check whether a single key is in the dictionary using the in keyword. This returns a Boolean.
  • list(dict) returns a list of all the keys in insertion order.
  • sorted(dict) returns the dictionary sorted according to key.
  • The dict() constructor builds dictionaries directly from sequences of key-value pairs.

CSE 160: Section 5

13 of 19

Section Handout Problems

CSE 160: Section 5

14 of 19

Problem 1

  1. Write a function called evens_and_odds() that takes two parameters, start and end, and returns a nested list composed of two lists. The first list contains all even numbers between start and end (both inclusive). The second list contains all odd numbers between start and end (both inclusive)

Sample outputs

evens_and_odds(0, 10)

[[0, 2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]

evens_and_odds(5, 15)

[[6, 8, 10, 12, 14], [5, 7, 9, 11, 13, 15]]

CSE 160: Section 5

15 of 19

Problem 2

Write a function called count_words(filename) that reads the file and returns the total number of words across all lines. The file is formatted so that each line is a sentence.

For example, if you had a file quotes.txt that contains:

Hi my name is Annie.

Let’s learn Python!

The returned value would of count_words(“quotes.txt”) be:

8

CSE 160: Section 5

16 of 19

Problem 3

Create def get_squares(number_list) that accepts a list of numbers as a parameter, and returns a dictionary mapping each number in the list to its square.

For Example:

nums = [1, 4, 4]

get_squares(nums) returns {1:1, 4:16}

Python Tutor

CSE 160: Section 5

17 of 19

Problem 4

Write coldest_city(city_temperatures) that takes in a dictionary and return the city (key) with the lowest temperature (value).

For Example:

city_temperatures = {‘Seattle’: 36, ’Cupertino’:39, ‘New York’:57}

coldest_city(city_temperatures) => returns “Seattle”

CSE 160: Section 5

18 of 19

Problem 5 Part a

Write function def pokemon_types(pokemon_dict) that takes parameter pokemon_dict and returns a new dictionary mapping each type of pokemon to the number of pokemon in pokemon_dict with that type.

For example, when

pokemon_dict = {"pikachu": "electric", "charmander": "fire", "charizard" : "fire"}

pokemon_types(pokemon_dict)​ => returns ​{“electric” : 1, “fire” : 2}

CSE 160: Section 5

19 of 19

Problem 5 Part b

Write def pokemon_types(pokemon_dict) that takes parameter pokemon_dict and returns a new dictionary mapping each type of pokemon to the list of pokemon with that type.

For example, when

pokemon_dict = {"pikachu": "electric", "charmander": "fire", "charizard": "fire"}

pokemon_types(pokemon_dict) returns =>

{‘electric’ : [‘pikachu’], ‘fire’: [‘charmander’, ‘charizard’]}

CSE 160: Section 5