Py4inf 09 Dictionaries

download Py4inf 09 Dictionaries

of 29

Transcript of Py4inf 09 Dictionaries

  • 8/17/2019 Py4inf 09 Dictionaries

    1/29

    Python DictionariesChapter 9

    Python for Informatics: Exploring Information

    www.pythonlearn.com

  • 8/17/2019 Py4inf 09 Dictionaries

    2/29

    Unless otherwise noted, the content of this course material is licensed under a Crea

    Commons Attribution 3.0 License.

    http://creativecommons.org/licenses/b/3.0/.

    Copright !0"0# Charles $everance

  • 8/17/2019 Py4inf 09 Dictionaries

    3/29

    What is a Collection?

    •A collection is nice eca!se we can p!t more tha"al!e in them an# carry them all aro!n# in onecon"enient pac$age.

    •We ha"e a !nch of "al!es in a single %"ariale&

    •We #o this y ha"ing more than one place %in& the"ariale.

    •We ha"e ways of %n#ing the #i&erent places in th"ariale

  • 8/17/2019 Py4inf 09 Dictionaries

    4/29

    What is not a %Collectio

    •'ost of o!r "ariales ha"e one "al!e in them ( wp!t a new "al!e in the "ariale ( the ol# "al!e iswritten

    ) python

    Python *.+.* ,r*+*:-9//0 1e ** *20 3:67CC 8../ ,Apple Comp!ter0 Inc. !il# +4-4 x ; * x ; 8 print x

    8

  • 8/17/2019 Py4inf 09 Dictionaries

    5/29

    A ist

    •A linear collection of "al!es that stay in or#er

    •Dictionary

    •A %ag& of "al!es0 each with its own lael

  • 8/17/2019 Py4inf 09 Dictionaries

    6/29

    Dictionarie

    s

    money

    calc!lator

    perf!me

    can#y

    http:en.wi$ipe#ia.orgwi$iAssociati"e@arra

  • 8/17/2019 Py4inf 09 Dictionaries

    7/29

    Dictionaries

    •Dictionaries are Python's most powerf!l #ata collecti•Dictionaries allow !s to #o fast #ataase(li$e operati

    Python

    •Dictionaries ha"e #i&erent names in #i&erent lang!a

    •Associati"e Arrays ( Perl Php

    •Properties or 'ap or ash'ap ( Ba"a

    •Property ag ( C .ethttp:en.wi$ipe#ia.orgwi$iAssociati"e@ar

  • 8/17/2019 Py4inf 09 Dictionaries

    8/29

    Dictionaries

    •>ists in#ex their entriesase# on the positionin the list

    •Dictionaries are li$eags ( no or#er

  • 8/17/2019 Py4inf 09 Dictionaries

    9/29

    Comparing >ists an#Dictionaries

    •Dictionaries are li$e >ists except that they !se $instea# of n!mers to loo$ !p "al!es

    lst ; list,5

    lst.appen#,*/5 lst.appen#,/245 print lst6*/0 /24 lst6 ; *4 print lst6*40 /24

    ### ; #ict, ###6FageF ;

    ###6Fco!rse print ###GFco!rseF: /2*0 Fa ###6FageF ; print ###

    GFco!rseF: /2*0 Fa

  • 8/17/2019 Py4inf 09 Dictionaries

    10/29

    lst ; list,5 lst.appen#,*/5 lst.appen#,/245 print lst

    6*/0 /24 lst6 ; *4 print lst6*40 /24

    ### ; #ict,5

    ###6FageF ; */ ###6Fco!rseF ; /2* print ###GFco!rseF: /2*0 FageF: */H ###6FageF ; *4 print ###

    GFco!rseF: /2*0 FageF: *4H

    6 */

    6/ /2

    Key L

    6Fco!rseF /

    6FageF *

    Key

    >ist

    Diction

  • 8/17/2019 Py4inf 09 Dictionaries

    11/29

    Dictionary >iterals,Constants5

    •Dictionary literals !se c!rly races an# ha"e a list of $ey : "

    • Mo! can ma$e an empty #ictionary !sing empty c!rly races

    NNN ; G Fch!c$F : / 0 Ffre#F : 8*0 F NanF print NNNGF NanF: /0 Fch!c$F: /0 Ffre#F: 8*H ooo ; G H print oooGH

  • 8/17/2019 Py4inf 09 Dictionaries

    12/29

    'ost Common ame

    cse"Ohen Ohen

    mar!ar#Ohen

    cwe

    mar!ar#Ohen

    mar!ar#cse" c

    Ohen

  • 8/17/2019 Py4inf 09 Dictionaries

    13/29

    'ost Common ame

  • 8/17/2019 Py4inf 09 Dictionaries

    14/29

    'ost Common ame

    cse"Ohen Ohen

    mar!ar#Ohen

    cwe

    mar!ar#Ohen

    mar!ar#cse" cOhen

  • 8/17/2019 Py4inf 09 Dictionaries

    15/29

    'any Co!nters with aDictionary

    •Qne common !se of #ictionary isco!nting how often we %see& something

    Key

    ccc ; #ict,5 ccc6Fcse"F ; / ccc6FcwenF ; / print cccGFcse"F: /0 FcwenF: /H ccc6FcwenF ; ccc6FcwenF / print cccGFcse"F: /0 FcwenF: *H

  • 8/17/2019 Py4inf 09 Dictionaries

    16/29

    Dictionary =raceac$

    • It is an error to reference a $ey which is not in the #ict

    •We can !se the in operator to see if a $ey is in the #ict ccc ; #ict,5 print ccc6Fcse"F =raceac$ ,most recent call last5:  1ile RSst#inR0 line /0 in Smo#!leKeyError: Fcse"F print Fcse"F in ccc1alse

  • 8/17/2019 Py4inf 09 Dictionaries

    17/29

    When we see a new na

    •When we enco!nter a new name0 we nee# to a## a new ent#ictionary an# if this the secon# or later time we ha"e seen we simply a## one to the co!nt in the #ictionary !n#er that

    counts = dict()

    names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']

    for name in names :  if name not in counts:

    counts[name] = 1

      else :

      counts[name] = counts[name] + 1

    print counts

    GFcse"F: *0 FOia

  • 8/17/2019 Py4inf 09 Dictionaries

    18/29

     =he get metho# for#ictionaries

    • =his pattern of chec$ingto see if a $ey is alrea#yin a #ictionary an#ass!ming a #efa!lt"al!e if the $ey is notthere is so common0that there is a metho# calle# get,5 that #oesthis for !s

      if name in co!  x ; co!nts6n  else :  x ; 

    x ; co!nts.get

    Defa!lt "al!e if $ey#oes not exist ,an# no

     =raceac$5.

    GFcse"F: *0 FOianF:

  • 8/17/2019 Py4inf 09 Dictionaries

    19/29

  • 8/17/2019 Py4inf 09 Dictionaries

    20/29

    http:www.yo!t!e.comwatch?";EB9!Mx+>

    counts = dict()

    names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']

    for name in names :

      counts[name] = counts.get(name, 0) + 1

    print counts

  • 8/17/2019 Py4inf 09 Dictionaries

    21/29

    Writing programs ,or programming5 is a "ery creati"e an#acti"ity. Mo! can write programs for many reasons rangma$ing yo!r li"ing to sol"ing a #iTc!lt #ata analysis prha"ing f!n to helping someone else sol"e a prolem. =

    ass!mes that e"eryone nee#s to $now how to program an

    yo! $now how to program0 yo! will %g!re o!t what yo! wwith yo!r newfo!n# s$ills.We are s!rro!n#e# in o!r #aily li"es with comp!ters ran

    laptops to cell phones. We can thin$ of these comp!teUUpersonal assistantsFF who can ta$e care of many thin

    ehalf. =he har#ware in o!r c!rrent(#ay comp!ters is essto contin!o!sly as$ !s the !estion0 UUWhat wo!l# yo! li

    next?FF.Q!r comp!ters are fast an# ha"e "asts amo!nts of memoe "ery helpf!l to !s if we only $new the lang!age to speato the comp!ter what we wo!l# li$e it to UU#o nextFF. If wlang!age we co!l# tell the comp!ter to #o tas$s on o!r were reptiti"e. Interestingly0 the $in#s of things comp!t

    est are often the $in#s of things that we h!mans %n# min#(n!min .

  • 8/17/2019 Py4inf 09 Dictionaries

    22/29

    the clown ran after the car an# the car ran intotent an# the tent fell #own on the clown an# the

  • 8/17/2019 Py4inf 09 Dictionaries

    23/29

    Co!nting Pattern

    counts = dict()

    print 'Enter a line of text:

    'line = raw_input('')

    words = line.split()

    print 'Words:', words

    print 'Counting...’

    for word in words:

      counts[word] = counts.get(word,0) + 1

    print 'Counts', counts

     =he general pco!nt the wor#stext is to split thwor#s0 then loo

    the wor#s an#ictionary to tracof each wor# in#

  • 8/17/2019 Py4inf 09 Dictionaries

    24/29

    Co!nting Wor#spython wor#co!nt.py Enter a line of text:the clown ran after the car an# the car ran intothe tent an# the tent fell #own on the clownan# the carWor#s: 6FtheF0 FclownF0 FranF0 FafterF0 FtheF0 FcarF0Fan#F0 FtheF0 FcarF0 FranF0 FintoF0 FtheF0 FtentF0Fan#F0 FtheF0 FtentF0 FfellF0 F#ownF0 FonF0 FtheF0

    FclownF0 Fan#F0 FtheF0 FcarFCo!nting...Co!nts GFan#F: 40 FonF: /0 FranF: *0 FcarF: 40FintoF: /0 FafterF: /0 FclownF: *0 F#ownF: /0 FfellF:/0 FtheF: 30 FtentF: *H

    http:www.Vic$r.comphotos3/+

  • 8/17/2019 Py4inf 09 Dictionaries

    25/29

    counts = dict()

    print 'Enter a line of text:'line = raw_input('')

    words = line.split()

    print 'Words:', words

    print 'Counting...’

    for word in words:

      counts[word] = counts.get(word,0) + 1print 'Counts', counts

    python wor#co!nt.pEnter a line of text:after the car an# ththe tent an# the ten

    on the clown an# th

    Wor#s: 6FtheF0 FclowFafterF0 FtheF0 FcarF0 FaFcarF0 FranF0 FintoF0 FthFan#F0 FtheF0 FtentF0 Ff

    FonF0 FtheF0 FclownF0 FFcarFCo!nting...

    Co!nts GFan#F: 40 FoFcarF: 40 FintoF: /0 FafFclownF: *0 F#ownF: /

    FtheF: 30 FtentF: *H

    D % it > #

  • 8/17/2019 Py4inf 09 Dictionaries

    26/29

    De%nite >oops an#Dictionaries

    •E"en tho!gh #ictionaries are not store# in or#er0 wewrite a for loop that goes thro!gh all the entries in #ictionary ( act!ally it goes thro!gh all of the $eys i#ictionary an# loo$s !p the "al!es

    co!nts ; G Fch!c$F : / 0 Ffre#F : 8*0 FNanF: /H for $ey in co!nts:... print $ey0 co!nts6$ey...

     Nan /ch!c$ /fre# 8*

    X t i i li t f K

  • 8/17/2019 Py4inf 09 Dictionaries

    27/29

    Xetrie"ing lists of Keys aLal!es

    • Mo! can get a list of$eys0 "al!es or items,oth5 from a #ictionary

    NNN ; G Fch!c$F : / print list,NNN56FNanF0 Fch!c$F0 Ffre#F print NNN.$eys,56FNanF0 Fch!c$F0 Ffre#F print NNN."al!es,56/0 /0 8* print NNN.items,56,

    What is a Ft!pleF?

    = It ti

  • 8/17/2019 Py4inf 09 Dictionaries

    28/29

    on!s: =wo IterationLarialesY

    •We loop thro!gh the$ey("al!e pairs in a#ictionary !sing ZtwoZiteration "ariales

    •Each iteration0 the%rst "ariale is the$ey an# the thesecon# "ariale is thecorresponding "al!efor the $ey

     NNN ; G Fch!c$F : / for aaa0 in NNN.i... print aaa0 ... Nan /ch!c$ /fre# 8*

    6c

    6

  • 8/17/2019 Py4inf 09 Dictionaries

    29/29