Lecture 14. Nested Lists and Dictionaries

Similar documents
Mini-Lecture 16. Nested Lists

Lecture 7. Scientific Computation

CS Lecture 26: Grab Bag. Announcements

Lecture 12. Lists (& Sequences)

Overview of List Syntax

Review 4. Lists and Sequences

Iteration and For Loops

CS Prelim 1 Review Fall 2017

Lecture 9. Memory and Call Stacks

Lecture 13. For-Loops

CS Prelim 1 Review Fall 2018

Lecture 7. Memory in Python

CS Prelim 1 Review Fall 2013

PREPARING FOR THE FINAL EXAM

CS Prelim 1 Review Fall 2016

Lecture 11: Iteration and For-Loops

CS 1110 Final, December 8th, Question Points Score Total: 100

Lecture 13. For-Loops

PREPARING FOR PRELIM 1

CS 1110: Introduction to Computing Using Python Lists and Sequences

CS 1110 Final, December 8th, Question Points Score Total: 100

CS Prelim 2 Review Fall 2018

CS 1110 Prelim 2 November 13th, 2014

CS Prelim 1 Review Fall 2013

CIS192: Python Programming

Lecture 26: Sorting CS 1110 Introduction to Computing Using Python

CS Prelim 1 Review Fall 2012

Announcements For This Lecture

PREPARING FOR THE FINAL EXAM

Lecture 10: Lists and Sequences

Programming Languages and Techniques (CIS120)

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

Announcements for This Lecture

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani

Lecture 5. Defining Functions

CS1110. Lecture 22: Prelim 2 Review Session. Announcements. Processed prelim regrade requests: on the front table.

CS 1110, Spring 2018: Prelim 1 study guide Prepared Tuesday March 6, 2018

Lecture 25. Sequence Algorithms (Continued)

COMPUTER SCIENCE IN THE NEWS (TWO YEARS AGO) CS61A Lecture 16 Mutable Data Structures TODAY REVIEW: OOP CLASS DESIGN 7/24/2012

Python Tutorial. CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi

CS 1110, LAB 12: SEQUENCE ALGORITHMS First Name: Last Name: NetID:

CS 1110 Prelim 2 November 10th, 2016

Announcements for This Lecture

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

CS 1110: Introduction to Computing Using Python Loop Invariants

CS1110 Lab 6 (Mar 17-18, 2015)

Data Structures. Dictionaries - stores a series of unsorted key/value pairs that are indexed using the keys and return the value.

Lecture 1. Course Overview, Python Basics

Python Programming: Lecture 2 Data Types

Programming for Electrical and Computer Engineers. Pointers and Arrays

Lecture 19. Operators and Abstraction

PREPARING FOR PRELIM 2

MUTABLE LISTS AND DICTIONARIES 4

Recap from last Python lecture

Programming Languages and Techniques (CIS120)

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017

Announcements for this Lecture

Lecture 10. Memory in Python

ENGR 102 Engineering Lab I - Computation

CS 1110 Final, December 16th, 2013

CS1110. Lecture 6: Function calls

Programming Languages

Lecture 1. Course Overview, Python Basics

CS61A Lecture 16 Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 16, 2012

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Collections. Lists, Tuples, Sets, Dictionaries

CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28) First Name: Last Name: NetID:

Lecture 15. More Recursion

CS Prelim 2 Review Fall 2017

Programming Languages

CS 1110 Prelim 1 October 17th, 2013

Python Workshop. January 18, Chaitanya Talnikar. Saket Choudhary

CS 102 Lab 3 Fall 2012

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Lists, Tuples and Dictionaries. HORT Lecture 10 Instructor: Kranthi Varala

COMP 204: Dictionaries Recap & Sets

Sequences and iteration in Python

Teaching London Computing

Lecture 7: Objects (Chapter 15) CS 1110 Introduction to Computing Using Python

Lecture 18. Classes and Types

Two Dimensional Arrays

Announcements. Lecture Agenda. Class Exercise. Hashable. Mutability. COMP10001 Foundations of Computing Iteration

CS Lecture 19: Loop invariants

Lecture 20. Subclasses & Inheritance

CIS192 Python Programming

UNIVERSITY OF TORONTO SCARBOROUGH. Fall 2015 EXAMINATIONS. CSC A20H Duration 3 hours. No Aids Allowed

CS 1110 Prelim 2 November 12th, 2015

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Exercise: The basics - variables and types

CS 1110 Prelim 2 November 14th, 2013

CS1110. Lecture 6: Function calls

Lecture 11. Asserts and Error Handling

Comp Exam 1 Overview.

CS 1110 Prelim 1 October 4th, 2012

Announcements For This Lecture

CS1110 Lab 1 (Jan 27-28, 2015)

HW0 v3. October 2, CSE 252A Computer Vision I Fall Assignment 0

CSC 108H: Introduction to Computer Programming. Summer Marek Janicki

Announcements COMP 141. Lab from Last Time. Dictionaries 11/29/2017. CS1: Programming Fundamentals

Transcription:

Lecture 14 Nested Lists and Dictionaries

Announcements for This Lecture Readings Today: Chapter 11 Next Week: Sec. 5.8-5.10 Prelim, Oct 12 th 7:30-9:00 Material up to TUESDAY Study guide is posted Review session Wednesday Still checking place/time Announcement on Piazza Assignments A3 is due today Survey is posted in CMS Late penalty 10%/day Opportunities for help Consultants 4:30-9:30 Will be on Piazza until Mid. No lab next week Tuesday part of Fall Break No special lab for Wed 10/5/17 Nested Lists and Dictionaries 2

Lists of Objects List positions are variables Can store base types r id10 id13 list But cannot store folders Can store folder identifiers Folders linking to folders b g x id11 id12 id13 x[0] x[1] x[2] id10 id11 id12 Top folder for the list Other folders for contents Example: >>> r = cornell.red >>> b = cornell.blue >>> g = cornell.green >>> x = [r,b,g] id10 RGB red 255 green 0 blue 0 id11 RGB red 0 green 255 blue 0 id12 RGB red 0 green 0 blue 255 10/5/17 Nested Lists and Dictionaries 3

Lists of Objects List positions are variables Can store base types r id10 id13 list But cannot store folders Can store folder identifiers Folders linking to folders b g x id11 id12 id13 x[0] x[1] x[2] id10 id11 id12 Top folder for the list Other folders for contents Example: >>> r = cornell.red >>> b = cornell.blue >>> g = cornell.green >>> x = [r,b,g] id10 RGB red 255 green 0 blue 0 id11 RGB red 0 green 255 blue 0 id12 RGB red 0 green 0 blue 255 10/5/17 Nested Lists and Dictionaries 4

Nested Lists Lists can hold any objects Lists are objects Therefore lists can hold other lists! a = [2, 1] b = [3, 1] c = [1, 4, b] x = [1, a, c, 5] x[1] x[2] x[2][2] x = [1, [2, 1], [1, 4, [3, 1]], 5] x[0] x[1][1] x[2][0] x[2][2][1] 10/5/17 Nested Lists and Dictionaries 5

Two Dimensional Lists Table of Data Images 0 1 2 3 0 1 2 3 4 5 6 7 8 9 10 1112 0 1 2 3 4 5 4 7 3 4 8 9 7 5 1 2 3 4 1 2 9 6 7 8 0 Each row, col has a value 0 1 2 3 4 5 6 7 8 9 10 11 12 Each row, col has an RGB value Store them as lists of lists (row-major order) d = [[5,4,7,3],[4,8,9,7],[5,1,2,3],[4,1,2,9],[6,7,8,0]] 10/5/17 Nested Lists and Dictionaries 6

Overview of Two-Dimensional Lists Access value at row 3, col 2: 0 1 2 3 d[3][2] Assign value at row 3, col 2: d[3][2] = 8 d 0 1 2 3 5 4 7 3 4 8 9 7 5 1 2 3 4 1 2 9 An odd symmetry 4 6 7 8 0 Number of rows of d: len(d) Number of cols in row r of d: len(d[r]) 10/5/17 Nested Lists and Dictionaries 7

How Multidimensional Lists are Stored b = [[9, 6, 4], [5, 7, 7]] b 9 6 4 5 7 7 id1 id1 id2 id3 id2 9 6 4 id3 5 7 7 b holds name of a one-dimensional list Has len(b) elements Its elements are (the names of) 1D lists b[i] holds the name of a one-dimensional list (of ints) Has len(b[i]) elements 10/5/17 Nested Lists and Dictionaries 8

Image Data: 2D Lists of Pixels 0 1 2 3 4 5 6 7 8 9 10 11 12 0 1 2 3 4 5 6 7 8 9 10 1112 b[0][0] is a white pixel id23 RGB red 255 green 255 blue 255 b id1 id1 list id2 list id2 id23 id3 id24 10/5/17 Nested Lists and Dictionaries 9

Ragged Lists: Rows w/ Different Length b = [[17,13,19],[28,95]] b id1 id2 id1 0 17 0 id2 0 1 13 1 id3 1 2 19 id3 28 95 Will see applications of this later 10/5/17 Nested Lists and Dictionaries 10

Slices and Multidimensional Lists Only top-level list is copied. Contents of the list are not altered b = [[9, 6], [4, 5], [7, 7]] x x = b[:2] id5 b id1 id2 id5 id1 id2 9 6 id3 id2 id3 id3 id4 id4 4 5 7 7 10/5/17 Nested Lists and Dictionaries 11

Slices and Multidimensional Lists Only top-level list is copied. Contents of the list are not altered b = [[9, 6], [4, 5], [7, 7]] x x = b[:2] id5 b id1 id2 id5 id1 id2 9 6 id3 id2 id3 id3 id4 id4 4 5 7 7 10/5/17 Nested Lists and Dictionaries 12

Slices and Multidimensional Lists Create a nested list >>> b = [[9,6],[4,5],[7,7]] Get a slice >>> x = b[:2] Append to a row of x >>> x[1].append(10) x now has nested list [[9, 6], [4, 5, 10]] What are the contents of the list (with name) in b? A: [[9,6],[4,5],[7,7]] B: [[9,6],[4,5,10]] C: [[9,6],[4,5,10],[7,7]] D: [[9,6],[4,10],[7,7]] E: I don t know 10/5/17 Nested Lists and Dictionaries 13

Slices and Multidimensional Lists Create a nested list >>> b = [[9,6],[4,5],[7,7]] Get a slice >>> x = b[:2] Append to a row of x >>> x[1].append(10) x now has nested list [[9, 6], [4, 5, 10]] What are the contents of the list (with name) in b? A: [[9,6],[4,5],[7,7]] B: [[9,6],[4,5,10]] C: [[9,6],[4,5,10],[7,7]] D: [[9,6],[4,10],[7,7]] E: I don t know 10/5/17 Nested Lists and Dictionaries 14

Functions and 2D Lists def transpose(table): """Returns: copy of table with rows and columns swapped Precondition: table is a (non-ragged) 2d List""" numrows = len(table) # Need number of rows numcols = len(table[0]) # All rows have same no. cols result = [] for m in range(numcols): # Result (new table) accumulator # Get the column elements at position m # Make a new list for this column # Add this row to accumulator table 1 2 3 4 5 6 1 3 5 2 4 6 return result 10/5/17 Nested Lists and Dictionaries 15

Functions and 2D Lists def transpose(table): """Returns: copy of table with rows and columns swapped Precondition: table is a (non-ragged) 2d List""" numrows = len(table) # Need number of rows numcols = len(table[0]) # All rows have same no. cols result = [] for m in range(numcols): row = [] for n in range(numrows): # Result (new table) accumulator # Single row accumulator row.append(table[n][m]) # Create a new row list result.append(row) return result # Add result to table 1 2 3 4 5 6 1 3 5 2 4 6 10/5/17 Nested Lists and Dictionaries 16

Functions and 2D Lists def transpose(table): """Returns: copy of table with rows and columns swapped Precondition: table is a (non-ragged) 2d List""" numrows = len(table) # Need number of rows numcols = len(table[0]) # All rows have same no. cols result = [] for m in range(numcols): row = [] for n in range(numrows): # Result (new table) accumulator # Single row accumulator row.append(table[n][m]) # Create a new row list result.append(row) return result Nest lists need nested loops # Add result to table 1 2 3 4 5 6 1 3 5 2 4 6 10/5/17 Nested Lists and Dictionaries 17

Dictionaries (Type dict) Description List of key-value pairs Keys are unique Values need not be Example: net-ids net-ids are unique (a key) names need not be (values) js1 is John Smith (class 13) js2 is John Smith (class 16) Many other applications Python Syntax Create with format: {k1:v1, k2:v2, } Keys must be non-mutable ints, floats, bools, strings Not lists or custom objects Values can be anything Example: d = {'js1':'john Smith', 'js2':'john Smith', 'wmw2':'walker White'} 10/5/17 Nested Lists and Dictionaries 18

Using Dictionaries (Type dict) Access elts. like a list d['js1'] evaluates to 'John' But cannot slice ranges! Dictionaries are mutable Can reassign values d['js1'] = 'Jane' Can add new keys d['aa1'] = 'Allen' Can delete keys del d['wmw2'] d = {'js1':'john','js2':'john', 'wmw2':'walker'} id8 'js1' 'js2' 'wmw2' d 'John' 'John' 'Walker' id8 dict Key-Value order in folder is not important 10/5/17 Nested Lists and Dictionaries 19

Using Dictionaries (Type dict) Access elts. like a list d['js1'] evaluates to 'John' But cannot slice ranges! Dictionaries are mutable Can reassign values d['js1'] = 'Jane' Can add new keys d['aa1'] = 'Allen' Can delete keys del d['wmw2'] d = {'js1':'john','js2':'john', 'wmw2':'walker'} id8 'js1' 'js2' 'wmw2' d 'John' 'Jane' 'John' 'Walker' id8 dict Key-Value order in folder is not important 10/5/17 Nested Lists and Dictionaries 20

Using Dictionaries (Type dict) Access elts. like a list d['js1'] evaluates to 'John' But cannot slice ranges! Dictionaries are mutable Can reassign values d['js1'] = 'Jane' Can add new keys d['aa1'] = 'Allen' Can delete keys del d['wmw2'] d = {'js1':'john','js2':'john', 'wmw2':'walker'} id8 'js1' 'js2' 'wmw2' 'aa1' d 'Jane' 'John' 'Walker' 'Allen' id8 dict 10/5/17 Nested Lists and Dictionaries 21

Using Dictionaries (Type dict) Access elts. like a list d['js1'] evaluates to 'John' But cannot slice ranges! Dictionaries are mutable Can reassign values d['js1'] = 'Jane' Can add new keys d['aa1'] = 'Allen' Can delete keys del d['wmw2'] d = {'js1':'john','js2':'john', 'wmw2':'walker'} id8 'js1' 'js2' 'wmw2' 'aa1' d 'Jane' 'John' 'Walker' 'Allen' id8 dict Deleting key deletes both 10/5/17 Nested Lists and Dictionaries 22

Dictionaries and For-Loops Dictionaries!= sequences Cannot slice them Different inside for loop Loop variable gets the key Then use key to get value Can extract iterators with dictionary methods Key iterator: d.keys() Value iterator: d.values() key-value pairs: d.items() for k in d: # Loops over keys print(k) # key print(d[k]) # value # To loop over values only for v in d.values(): print(v) # value See grades.py 10/5/17 Nested Lists and Dictionaries 23