1 of 6

CSE 163

CSVs and Lists of Dictionaries

��Hunter Schafer

💬 On a scale from bat to plant, how much do you enjoy the sun being out more?

🎵 Music: Dr. Dog

2 of 6

This Time

  • Dictionary Methods
    • How to loop over dictionary
  • CSVs
  • List of Dictionaries

Last Time

  • List Comprehensions
  • Tuple
  • Sets
  • Dictionaries

2

3 of 6

Dictionary Methods

  • Dictionary Methods

3

dict() or {}

Makes an empty dictionary

d[key]

Gets the value for k, KeyError if None

d[key] = val

Assigns val as the value for key

d.pop(key)

Removes key from this dictionary

d.keys()

Returns a collection of the keys

d.values()

Returns a collection of the values

d.items()

Returns a collection of (key, value) tuples

4 of 6

Processing CSVs

  • Well structured so they are easy to parse!
  • Not clear how to represent since we need info on rows and cols. Have to use multiple data structures!

  • We will use a list of dictionaries to store this information

4

Name,Salary

Madrona,3

Ken,1

Ryan,3

[

{'Name': 'Madrona', 'Salary': 3},

{'Name': 'Ken', 'Salary': 1},

{'Name': ‘Ryan’, 'Salary': 3}

]

5 of 6

Processing CSVs

  • Be careful of the types!

5

# data is a list containing dictionaries

tas = cse163_utils.parse('tas.csv')

# tas[0] is a dictionary

madrona = tas[0]

# madrona['Salary'] is an int

madrona['Salary']

# Also works without an intermediate variable

tas[0]['Salary']

# Doesn't work! List doesn't allow string indices

tas['Salary'][0]

6 of 6

Group Work:

Best Practices

When you first working with this group:

  • Introduce yourself!
  • If possible, angle one of your screens so that everyone can discuss together

Tips:

  • Starts with making sure everyone agrees to work on the same problem
  • Make sure everyone gets a chance to contribute!
  • Ask if everyone agrees and periodically ask each other questions!
  • Call TAs over for help if you need any!

6