The grand finale!
Data structures, writing CSV files & wrap-up

Tips for navigating the slides:
  • Press O or Escape for overview mode.
  • Visit this link for a nice printable version
  • Press the copy icon on the upper right of code blocks to copy the code

Class outline:

  • Review
  • Tuples
  • Dictionaries
  • Writing CSV files
  • Putting it all together
  • Where to go from here?

Review

Checking if value is in a list

The in keyword checks if a value is in a list (or any sequence).


                    if "bananas" in groceries:
                        print("Watch your step!")

                    if "bleach" in groceries:
                        print("Watch what you eat!")
                    

When used inside if conditions, in expressions return a Boolean (True/False).

Helpful list methods

Method Description
count(item) Returns the number of occurrences of item in the list. If item is not found, returns 0.
reverse() Reverses the elements of the list in place.
sort([key=function]) Sorts the items of the list in place. The optional key argument specifies a function to compute a comparison key for each item in the list. Otherwise, items are compared based on their values.

For more about list methods, seePython.org documentation

Useful built-in functions for lists

These are functions, not methods.

Module Function Description
Global min(list, [key=function]) Returns the minimum value in list. The optional key argument specifies a custom comparator function.
Global max(list, [key=function]) Returns the maximum value in list. he optional key argument specifies a custom comparator function.
random choice(list) Returns a randomly selected item from list.
random shuffle(list) Shuffles the elements of the list in place.

For more on built-in functions see Python.org documentation. Functions that work with lists are those that accept an "iterable" as an argument.

Nested Lists

Since Python lists can contain any values, an item can itself be a list.

                    
                    gymnasts = [
                                    ["Brittany", 9.15, 9.4, 9.3, 9.2], # gymnasts[0]
                                    ["Lea", 9, 8.8, 9.1, 9.5], # gymnasts[1]
                                    ["Maya", 9.2, 8.7, 9.2, 8.8] # gymnasts[2]
                               ]
                    

You can think of nested lists like rows in a table:

Accessing nested list items


                    gymnasts = [
                                    ["Brittany", 9.15, 9.4, 9.3, 9.2],
                                    ["Lea", 9, 8.8, 9.1, 9.5],
                                    ["Maya", 9.2, 8.7, 9.2, 8.8]
                                ]
                    

Access using bracket notation, with more brackets as needed:


                    gymnasts[0]    # ["Brittany", 9.15, 9.4, 9.3, 9.2]
                    gymnasts[0][0] # "Brittany"
                    gymnasts[1][0] # "Lea"
                    gymnasts[1][4] # 9.5
                    gymnasts[1][5] # ๐Ÿšซ IndexError!
                    gymnasts[3][0] # ๐Ÿšซ IndexError!
                    

Modifying nested lists: Bracket notation


                    gymnasts = [
                                    ["Brittany", 9.15, 9.4, 9.3, 9.2],
                                    ["Lea", 9, 8.8, 9.1, 9.5],
                                    ["Maya", 9.2, 8.7, 9.2, 8.8]
                                ]
                    

Modify using bracket notation as well, just like before:


                    gymnasts[0] = ["Olivia", 8.75, 9.1, 9.6, 9.8]
                    gymnasts[1][0] = "Leah"
                    gymnasts[2][4] = 9.8
                    

Modifying nested lists: List methods

If we start with...


                    gymnasts = [
                                    ["Brittany", 9.15, 9.4, 9.3, 9.2],
                                    ["Lea", 9, 8.8, 9.1, 9.5]
                               ]
                    

We can append another list a few ways:


                    gymnasts.append(["Maya", 9.2, 8.7, 9.2, 8.8])
                    

                    gymnast = []
                    gymnast.append("Maya")
                    gymnast.append(9.2)
                    gymnast.append(8.7)
                    gymnast.append(9.2)
                    gymnast.append(8.8)
                    gymnasts.append(gymnast)
                    

Looping through nested lists


                    gymnasts = [
                                    ["Brittany", 9.15, 9.4, 9.3, 9.2],
                                    ["Lea", 9, 8.8, 9.1, 9.5],
                                    ["Maya", 9.2, 8.7, 9.2, 8.8]
                                ]
                    

Use a nested for-in loop:


                    for gymnast in gymnasts:
                        print(gymnast)
                        for data in gymnast:
                            print(data)
                    

Remember what type of data is being stored in the loop variable!

CSV files

Comma Separated Value (CSV) is a plain text format used to store "tabular" data (aka rows and columns), like from a spreadsheet or database table.

Because CSV is simple and non-proprietary, it's commonly used to exchange data between different applications.


                        Brittany, 9.15, 9.4, 9.3, 9.2
                        Lea, 9, 8.8, 9.1, 9.5
                        Maya, 9.2, 8.7, 9.2, 8.8
                    

Opening files

We use the Python built in open() method to open files for reading or writing.

The keyword with tells Python to automatically close the file when we're finished.


                        with open('filename') as my_file:
                            # do something
                    

See the docs on python.org for more

Reading files with CSV module

Python has a built-in CSV module that includes many features used for reading/writing CSV files.

Open a CSV and read its contents (docs at python.org)

                        # import the csv module
                        import csv
                        # open the file
                        with open('fun_spreadsheet.csv') as my_file:
                            # load the contents of the CSV file into a variable
                            csv_reader = csv.reader(my_file)
                            # CSV is a nested list!
                            # now we can loop through the rows in the file
                            for row in csv_reader:
                                print(row)
                    

Reading files with CSV module

A CSV is a list of rows, which are lists of values.

We can use nested for loops to get values from rows and cells.


                        import csv
                        with open('fun_spreadsheet.csv') as my_file:
                            csv_reader = csv.reader(my_file, delimiter=',')
                            for row in csv_reader:
                                print(row)
                                for cell in row:
                                    print(cell)
                    

Homework review!

Repl: Class4Ex5NestedForLoops

More data structures!

Tuples

A tuple is like a list, but immutable: its values cannot be changed after the initialization.

Tuples are enclosed in parentheses (9.99, 7.99, 3.99)


                    position = (100, 50)
                    prices = (9.99, 7.99, 3.99)
                    

You can still access items in a tuple:


                    position = (100, 50)
                    x = position[1]
                    y = position[2]
                    

Or iterate through:


                    total = 0
                    for price in prices:
                        total += price
                    

Tuple immutability

All of these operations will result in an error:


                    position = (100, 50)

                    position[0] = 50
                    position[1] = 10
                    position.append(10)
                    

When to use tuples?

When you have list that won't change as your program runs. Tuples are much more memory efficent than lists. Your code will run much faster!

Dictionaries

A dict is a mutable mapping of key-value pairs


					states = {
						"CA": "California",
						"DE": "Delaware",
						"NY": "New York",
						"TX": "Texas",
						"WY": "Wyoming"
					}
					

Dictionaries allow you to access values using a human-readable name ("key") rather than an index number. Dictionaries map very well to JSON!

Dictionary Class1Ex1OperatorExpressions


					>>> len(states)
					5
					

					>>> "CA" in states
					True
					

					>>> "ZZ" in states
					False
					

Dictionary selection


					words = {
						"mรกs": "more",
						"otro": "other",
						"agua": "water"
					}
					

Select a value:


					>>> words["otro"]
					'other'
					

					>>> first_word = "agua"
					>>> words[first_word]
					'water'
					

					>>> words["pavo"]
					KeyError: pavo
					

Dictionary mutation

Create an empty dict:


					users = {}
					

Add values:


					users["liz"] = "b3stp@ssEvErDontHackMe"
					

Change values:


					users["liz"] = "itsLongerSoItsMoreSecure!!"
					

					>>> users["liz"]
					'itsLongerSoItsMoreSecure!!'
					

Dictionary rules

  • A key cannot be a list or dictionary (or any mutable type)
  • All keys in a dictionary are distinct (there can only be one value per key)
  • The values can be any type, however!

					spiders = {
					  "smeringopus": {
						  "name": "Pale Daddy Long-leg",
						  "length": 7
					  },
					  "holocnemus pluchei": {
						  "name": "Marbled cellar spider",
						  "length": (5, 7)
					  }
					}
					

Dictionary iteration


					insects = {"spiders": 8, "centipedes": 100, "bees": 6}
                    for insect in insects:
                        print("Key is " + insect)
                        # ex insects['spiders']
                        print("Value is " + str(insects[insect]))
					

What will be the order of items?


					8 100 6
					

Keys are iterated over in the order they are first added.

Dictionary iteration: A short-hand way

The .items() dictionary method returns a list containing a tuple for each key/value pair


					insects = {"spiders": 8, "centipedes": 100, "bees": 6}
                    for key, value in insects.items()
                        print("Key is " + key)
                        print("Value is " + str(value))
					

More dictionary methods

Exercise: Dictionaries

Reading CSV files as dictionaries

Reading CSV files with headers

Python has a built-in CSV module that includes many features used for reading/writing CSV files.

Open a CSV and read its contents

                        # import the csv module
                        import csv
                        # open the file
                        with open('fun_spreadsheet.csv') as my_file:
                            # load the contents of the CSV file into a variable
                            csv_reader = csv.DictReader(my_file)
                            # CSV is read as a dictionary with column headers as keys!
                            # now we can loop through the rows in the file
                            # and get the values from specific columns
                            for row in csv_reader:
                                print(row)
                    

Exercise: CSV with headers

Let's re-visit our gradebook exercise...

Writing CSV files

Writing files with CSV module

Python's built-in CSV module also has support for writing files (docs at python.org)


                        # import the csv module
                        import csv
                        my_list = [
                                ["Mon", "Oatmeal", "Salad", "Pasta"],
                                ["Tues", "Waffles", "Soup", "Tacos"],
                                ["Wed", "Cereal", "Sandwich", "Pizza"]
                            ]
                        # open a new or existing file for writing
                        with open('fun_spreadsheet.csv', 'w') as my_file:
                            # prepare the CSV for writing
                            writer = csv.writer(my_file)
                            # write data from a list to the CSV file
                            writer.writerows(my_list)
                    

Putting it all together

We learned so much!

  • Data types/expressions
  • Variables
  • Functions
  • Conditionals (if/else)
  • Loops (while, for/in)
  • Data structures (lists, tuples, dictionaries)
  • Reading/writing CSV files

Wrap-up project: Pizza order

Let's put it all together in one final exercise!

Repl: Class6Ex3PizzaOrder

What's next?! ๐ŸŽ‰ ๐Ÿ

Learning opps

  • GDI Python 2 Cohort (next session June 13-29)
  • Self-paced learning: Real Python tutorials are great
  • Check your local community college - most offer online Python and other programming courses
  • Learning opps: Coursera courses

  • University of MI Python for Everybody
  • University of MI Python 3 Programming
  • Google IT Automation with Python Certificate
  • But really, you need to practice coding!

    Hands-on project ideas:

    Next topics to explore

    • Error handling
    • Working with files
    • Getting data from APIs/databases
    • Installin Python on your computer & managing Python packages with PIP

    Building Python web apps

    Frameworks like Django and Flask are commonly used to build web apps quickly

    Feedback survey

    Please fill out the GDI feedback survey to help us improve future classes. Thanks!