1 of 21

CSE 160 Section 5

File I/O and Dictionaries!

2 of 21

Logistics

  • Written check-in 4 due Friday Oct 24
  • Coding practice 4 due Sunday Oct 26
  • HW3 due October 31
    • Submitting on Gradescope
    • Wait for autograder!
  • Resubmissions due Friday Oct 24 @ 11PM
    • Don’t forget to fill out the resubmission form!

3 of 21

Lecture Review: File I/O

4 of 21

File I/O

my_file = open(filepath)

for line_of_text in my_file:

# process line_of_text

my_file.close()

5 of 21

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”]

6 of 21

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”]

7 of 21

Lecture Review: Dictionary

8 of 21

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

9 of 21

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

10 of 21

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)

11 of 21

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.

12 of 21

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.

13 of 21

Section Handout Problems

14 of 21

Problem 1

You have a file named students.txt where each line contains a student's name and age separated by a comma, like this:

Alice,20�Bob,22

Write a program that reads the file and prints each student's name and age separately.

Example output:

Name: Alice, Age: 20

15 of 21

Problem 1

students_file = open("students.txt"):

for line in students_file:

parts = line.split(",")

name = parts[0]

age = parts[1]

print("Name:", name, "Age:", age)

students_file.close()

16 of 21

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

17 of 21

Problem 2

def count_words(filename):

word_count = 0

my_file = open(filename):

for line in my_file:

words = line.split()

word_count += len(words)

return word_count

18 of 21

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

19 of 21

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”

Python Tutor

20 of 21

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}

Python Tutor

21 of 21

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’]}

Python Tutor