CSC 1010 Lecture 8 What do we know so far? Class lecture, lab, - - PDF document

csc 1010 lecture 8
SMART_READER_LITE
LIVE PREVIEW

CSC 1010 Lecture 8 What do we know so far? Class lecture, lab, - - PDF document

CSC 1010 Lecture 8 What do we know so far? Class lecture, lab, Rephactor, Quick Checks, R&R, easter eggs Solve problems, computers useful, user vs. programmer Sequence of instructions, algorithm is step by step CSC


slide-1
SLIDE 1

CSC 1010 Lecture 8 1

CSC 1010 Programming for All

Lecture 8 Dictionaries

What do we know so far?

  • Class – lecture, lab, Rephactor, Quick Checks, R&R, easter eggs
  • Solve problems, computers useful, user vs. programmer
  • Sequence of instructions, algorithm is step‐by‐step
  • Python is 3rd most popular language, core principles, always more than one way
  • Syntax, runtime, & logic errors, testing & debugging, hardware vs. software
  • Control flow – step‐by‐step, function call, conditional, loop
  • IDLE shell, editor, install Python, Hello World
  • Intrepreter, compiler, Python Standard Library
  • Variables, assignment, numeric expr., precedence
  • Print function, Strings, concatenation, indexes, in, *
  • Interactive programs, if, if‐else, if‐elif‐else, int, float
  • Boolean expressions: ==, !‐, <, <=, >, >=, not, and, or
  • Input function, comparing strings, programming conventions
  • Variable & function names lowercase, CONSTANTS, indent
  • while, for, range, augmented assignments, palindromes
  • Turtle Graphics, forward, left, right, pensize, pencolor, dot, circle
  • goto, penup, pendown, fillcolor, begin_fill, end_fill, speed
  • Calling & defining functions, import, parameters vs. arguments, return
  • Positional args, default args, variable args, keyword args, local variables
  • String methods, replace, method vs. function, built‐in & external functions
  • Using loops and functions to create graphics, random numbers, design process
  • Lists: indexing, iterating, concatenating, containment, repetition
  • Membership: in & not in, Identity: is & is not, type checking
  • List algorithms, list methods, slicing strings and lists, ex: finding a minimum

2

Dictionaries

A Python dictionary is an unordered, changeable, and indexed collection of keys and corresponding values.

3

The keys and values can be of any type. Often, each key are a single string or integer. The types of each value are more varied, such as strings, integers, and lists of multiple values.

Uses of Dictionaries

  • Map a U.S. state name to its capital city.
  • Map a membership number to the corresponding member.
  • Map a sports team to the name of the city in which that

team is based.

  • Map a word to its frequency count (how often that word is

found in some text).

  • Map a zip code to the corresponding city name (or other

location description).

  • Map a software version number to the year it was released.
  • Map an English word to the corresponding French word.
  • Map a manager to the list of employees that work for that

manager.

  • Map a course id to the list of students taking that course.

4

Creating Dictionaries

You define a dictionary in Python with curly braces ({}):

5

capi t al s = { }

The dict function also works with named arguments:

{ ' Cal i f or ni a' : ' Sacr am ent o' , ' New Yor k' : ' Al bany' , ' M ar yl and' : ' Annapol i s' , ' Del awar e' : ' Dover ' } I know 4 st at e capi t al s!

Initializing a dictionary with keys and values works like this:

capi t al s = { ' M ar yl and' : ' Annapol i s' , ' New Yor k' : ' Al bany' , ' Cal i f or ni a' : ' Sacr am ent o' , ' Del awar e' : ' Dover ' } pr i nt ( capi t al s) pr i nt ( ' I know' , l en( capi t al s) , ' st at e capi t al s! ' )

Looking Up Values

The values in a dictionary can be accessed individually using a key inside the index operator.

6

cap = capi t al s[ ' New Yor k' ] pr i nt ( ' The capi t al of New Yor k i s' , cap) The capi t al of New Yor k i s Al bany

If the value is not found, a KeyError is reported. The safer way is using get, which returns a None value if the key is missing.

pr i nt ( " Del awar e' s capi t al i s" , capi t al s. get ( ' Del awar e' ) )

Del awar e' s capi t al i s Dover

1 2 3 4 5 6

slide-2
SLIDE 2

CSC 1010 Lecture 8 2

Changing and Adding Entries

To change the value of a dictionary entry, use its key.

7

capi t al s[ ' New Yor k' , ' Bi sm ar k' ] pr i nt ( " New Yor k' s capi t al i s" , capi t al s[ ' New Yor k' ] ) New Yor k' s capi t al i s Bi sm ar k

This replaces the value for 'New York' with a new one. To add a new entry to the dictionary, use a new key:

capi t al s[ ' Texas' ] = ' Aust i n' pr i nt ( ' The capi t al of Texas i s' , capi t al s[ ' Texas' ] ) The capi t al of Texas i s Aust i n

Removing Entries

To remove the value of a dictionary entry, use its key.

8

capi t al s. pop( ' Vi r gi ni a' ) pr i nt ( capi t al s)

The capitals dictionary will no longer have the removed

  • entry. An entry can also be removed using del.

del capi t al s[ ' Vi r gi ni a' ]

Use clear to remove all entries in a dictionary.

capi t al s. cl ear ( )

Key Existence

To avoid a KeyError when accessing a dictionary element that doesn't exist, use the in operator.

9

i f ' Fl or i da' i n capi t al s: pr i nt ( ' Fl or i da' s capi t al : ' , capi t al s[ ' Fl or i da' ] ) el se: pr i nt ( " I don' t know t he capi t al of Fl or i da! " ) I don' t know t he capi t al of Fl or i da!

You can also use the not in operator on a dictionary, which returns true if the key is not in the dictionary.

Iterating a Dictionary

Iterate the keys in a dictionary using a for loop.

10

f or key i n capi t al s: pr i nt ( key)

Iterate the values in a dictionary with the values method.

f or val ue i n capi t al s. val ues( ) : pr i nt ( val ue)

A common way to iterate keys and values is this:

f or key i n capi t al s: pr i nt ( capi t al s[ key] , ' i s capi t al of ' , key)

Dictionary Methods

11

Reading Text Files

To read input from a text file, use open and read. The open method creates a file object using a filename. The read method reads all text from the file into a string.

12

f i l e = open( ' i nput _dem

  • . t xt ' , ' r ' )

t ext = f i l e. r ead( ) pr i nt ( t ext )

Use readline to read one line at a time.

whi l e Tr ue: l i ne = f i l e. r eadl i ne( ) i f l i ne == ' ' : br eak l i nes = f i l e. r eadl i nes( )

Use readlines to read all lines into a list of strings.

7 8 9 10 11 12

slide-3
SLIDE 3

CSC 1010 Lecture 8 3

Writing Text Files

To write output to a text file, use open and write. The open method needs a 'w' argument to indicate the file is for writing.

13

f i l e = open( ' l yr i cs. t xt ' , ' w' ) f i l e. wr i t e( ' Hel l o, W

  • r l d! \ n' )

f i l e. wr i t e( ' And hel l o t o you! \ n' ) f i l e. cl ose( )

Note the newline (\n) character is used to end each line. It is important to close the file when you are done writing.

File Choosers: Open

The askopenfilename method opens a file selection dialog.

14

f r om t ki nt er i m por t Tk f r om t ki nt er . f i l edi al og i m por t askopenf i l enam e Tk( ) . wi t hdr aw( ) # Hi des t he def aul t wi ndow f i l enam e = askopenf i l enam e( )

File Choosers: Save

The asksaveasfilename method opens a file saving dialog.

15

f r om t ki nt er i m por t Tk f r om t ki nt er . f i l edi al og i m por t asksaveasf i l enam e Tk( ) . wi t hdr aw( ) # Hi des t he def aul t wi ndow f i l enam e = asksaveasf i l enam e( )

File Choosers: Directory

The askdirectory method opens a directory chooser dialog.

16

f r om t ki nt er i m por t Tk f r om t ki nt er . f i l edi al og i m por t asksaveasf i l enam e Tk( ) . wi t hdr aw( ) # Hi des t he def aul t wi ndow di r nam e = askdi r ect or y( )

Example: Counting Letters

17

t ext = ' ' ' I have a dr eam t hat m y f our l i t t l e chi l dr en wi l l one day l i ve i n a nat i on wher e t hey wi l l not be j udged by t he col or

  • f t hei r ski n but by t he cont ent of t hei r char act er . ' ' '

count s = { } f or l et t er i n t ext . upper ( ) : i f l et t er . i sal pha( ) : i f l et t er not i n count s: count s[ l et t er ] = 1 el se: count s[ l et t er ] += 1 pr i nt ( ' Let t er f r equenci es: ' ) pr i nt ( count s)

An entry in the counts dictionary is created or incremented for each character. The for loop iterates through each character.

13 14 15 16 17