0% found this document useful (0 votes)
20 views47 pages

17 Dictionaries

Uploaded by

eeenba c5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views47 pages

17 Dictionaries

Uploaded by

eeenba c5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

17.

Dictionaries

Topics:
Basic dictionary manipulations
How they are different from lists
Dictionaries are Objects
Application: Word frequency
A First Example

D = {‘I’:1,’V’:5,’X’:10,’L’:50,’C’:100}

This dictionary has 5 items:

’I’:1
’V’:5
’X’:10
’L’:50
’C’:100
Keys and Values

D = {‘I’:1,’V’:5,’X’:10,’L’:50,’C’:100}

An item has a key and a value.

For the item ’V’:5

‘V’ is the key


5 is the value
Set-Up
D = {‘I’:1,’V’:5,’X’:10,’L’:50,’C’:100}

To set up a small dictionary in this style, you do


this:

1. Use a colon to separate a key from its value.

2. Separate items with a comma.

3. Enclose the whole thing with curly brackets.


The Methods .keys and .values

>>>D={'I':1,'V':5,'X':10,'L':50,'C':100}

>>> D.keys() Creates a list of all


the keys
['I', 'X', 'C', 'L', 'V']

>>> D.values() Creates a list of all the


values
[1, 10, 100, 50, 5]
Deleting a Dictionary Item with del

>>>D={'I':1,'V':5,'X':10,'L':50,'C':100}

>>> del D[‘X’]

>>> D
{'I':1,'V':5,'L':50,'C':100}
Some Questions
• How do you check if a dictionary has a key?

• How do you access items in a dictionary?

• How can you add an item to a dictionary?

• How is a dictionary different from a list?

• Are there type-related rules about keys?

• Are there type-related rules about values?


Checking to see if a Dictionary
Has a Particular Key

>>> D = {'I':1,'V':5,'X':10}
>>> 'I' in D
True

>>> 'II' in D
False
>>>

Use in to check if a dictionary has a particular key.


Checking if D has a particular
Value Using the values Method

>>> D = {'I':1,'V':5,'X':10}
>>> L = D.values() Produce a list of
all the values in D
>>> L
[1, 10, 5]
>>> 5 in L Use “in” on
that list
True
Extracting a Value

>>> D = {'I':1,'V': 5,'X':10}


>>> a = D[‘V’]
>>> a
5

Use square bracket notation.

Use the key as you would an integer subscript.


Adding an Item to a Dictionary

>>> D = {'I':1,'V':5,'X':10}
>>> D['C'] = 100
>>> D
{'I': 1, 'X': 10, 'C': 100, 'V': 5}

Use assignment, e.g., D['C'] = 100

This “connects” the assigned value to the key named


within square brackets, making the pair an item,
e.g., 'C': 100
Changing the Value of an Item

>>> D = {'I':1,'V':5,'X':10}
>>> D[‘V'] = 55
>>> D
{'I':1, 'X':10, 'V':55}

D[‘V'] = 55 does not produce

{'I':1, ‘V’:5, 'X':10, 'V':55}

Cannot have two items with the same key.


Dictionaries are Different
from Lists

>>> D = {'I':1,'V':5,'X':10,'L':50}

>>> D
{'I': 1, 'X': 10, 'L': 50, 'V': 5}

The items in a dictionary are not ordered as in a


list.

We see here that Python “shows” a different


ordering than how D was set up.
Dictionaries are Different
From Lists
Dictionary values are accessed by key not subscript.

>>> D = {'I': 1, 'X': 10, 'V': 5}


>>> D['X']
Dictionary
10

>>> L = [1,5,10] List


>>> L[1]
5
Dictionaries are Different
From Lists
Dictionary values are accessed by key, not
subscript.

>>> D = {'I': 1, ‘V': 5, ‘X': 10}


>>> D[2]
Traceback (most recent call last): File
"<stdin>", line 1, in <module>
KeyError: 2

Python is complaining because 2 is not a key in the D


Lists and Dictionaries
x ---> 0 ---> 3 >>> x = []
1 ---> 5 >>> x.append(3)
2 ---> 1 >>> x.append(5)
>>> x.append(1)

D ---> ‘I’ ---> 1 >>> D = {}


‘V’ ---> 5 >>> D[‘I’] = 1
‘X’ ---> 10 >>> D[‘V’] = 5
>>> D[‘X’] = 10

Lists involve mappings from ints to values


Dictionaries involve mappings from keys to values
Lists and Dictionaries
x ---> 0 ---> 3 >>> x = []
1 ---> 5 >>> x.append(3)
2 ---> 1 >>> x.append(5)
>>> x.append(1)

D ---> ‘I’ ---> 1 >>> D = {}


‘V’ ---> 5 >>> D[‘I’] = 1
‘X’ ---> 10 >>> D[‘V’] = 5
>>> D[‘X’] = 10

You “add” to a list using the append method.


You add an item to a dictionary using a “new” key.
Lists and Dictionaries
x ---> 0 ---> 3 >>> L = [] Empty List
1 ---> 5 >>> L.append(3)
2 ---> 1 >>> L.append(5)
>>> L.append(1)

D ---> ‘I’ ---> 1 >>> D = {} Empty Dict


‘V’ ---> 5 >>> D[‘I’] = 1
‘X’ ---> 10 >>> D[‘V’] = 5
>>> D[‘X’] = 10

L = [ ] and L = list() are equivalent


D = { } and D = dict() are equivalent
Dictionaries & Lists
Access via the Square Bracket Notation:

D[‘x’] L[2]

The len function can be applied to both:

>>> x = [10,20,30]
>>> len(x)
3

>>> D = {'a':10,'b':20,'c':30}
>>> len(D)
3
Dictionaries & Lists Are Objects

>>> x = [10,20,30]
>>> y = x You can have multiple
>>> x[0]=100 references to the same
object. This is the idea of an
>>> y alias.
[100, 20, 30]

>>> D = {'a':10,'b':20,'c':30}
>>> E = D
>>> D['a'] = 100
>>> E
{'a': 100, 'c': 30, 'b': 20}
Dictionaries & Lists Are Objects

>>> x = [10,20,30]
>>> y = list(x) It is possible to
>>> x[0] = 100 make copies.
>>> y
[10, 20, 30]

>>> D = {'a':10,'b':20,'c':30}
>>> E = dict(D)
>>> D['a']=100
>>> E
{'a': 10, 'c': 30, 'b': 20}
For-Loops and Dictionaries
D = {‘I’:1,’V’:5,’X’:10,’L’:50}
for d in D:
print(d, D[d])

Again, dictionaries are


I 1
not ordered. So extra
X 10 steps would need
L 50 to be taken here for
V 5 things to be printed in a
certain order.
For-Loops and Dictionaries
D = {‘I’:1,’V’:5,’X’:10,’L’:50}
KeysOfD = D.keys()
KeysOfD.sort()
for d in KeysOfD:
print(d, D[d])

I 1
L 50
V 5
X 10
Pretty Printing a Short
Dictionary

>>> D = {'I':1,'V':5,'X':10,'L':50}

>>> str(D)

"{'I': 1, 'X': 10, 'L': 50, 'V': 5}"


Other Examples and Rules

D1 = {‘red’:[1,0,0],’cyan’:[0,1,1]}

D2 = {1:’one’, 2:’two’, 3:’three’}

D3 = {‘A’:’B’, 1:’C’, ‘D’:2}

- Keys must be strings or numbers


- Values can be anything
-Typically, the items all “look alike”, but that is not
necessary.
Some Common Errors
>>> D = {'I':1,'V':5,'X':10}

>>> D('I')

Traceback (most recent call last):


File "<stdin>", line 1, in <module>

TypeError: 'dict' object is not callable

Square brackets, not parens!


Some Common Errors
>>> D = {'I': 1, 'X': 10, 'V': 5}

>>> x = D['L']

Traceback (most recent call last):


File "<stdin>", line 1, in <module>

KeyError: 'L'

Trying to access a nonexistent item.

Note: D[‘L’] = 50 is legal and adds an item to D


A Dictionary Application

Given a text file F that encodes (for example) an


English novel, create a dictionary D that
specifies the frequency of each word that
appears in the file.
Word Frequency Dictionaries
The dictionary

D = {‘sun’:34,‘moon’:5,’darcy’:56}

would “say” that there are

34 occurrences of ‘sun’,
5 occurrences of ‘moon’, and
56 occurrences of ‘darcy’.
Strategy

First, read the file and create a list of strings, one


string for each line in the file:

L = FileToList('PridePrej.txt')
Strategy
Second, assume the existence of a function that
can extract a list of words from a string s and use
it like this:

wList = stringToWordList(s)

Thus, we would get

[‘the’,‘quick’,’brown’,’fox’]
from
‘The quick, brown fox!’
Strategy
Third, figure out how to update the word
frequency dictionary D:

L = fileToStringList(‘PridePrej.txt’)
D = {}
for s in L:
wList = stringToWordList(s)
for w in wList:
Update(w,D)
Updating a Dictionary

W = [‘cat’, mouse’,’dog’,’cat’,rabbit’]

D ---> ‘cat’ ---> 20


‘dog’ ---> 10

Look at each word in W and update D accordingly


Updating a Dictionary

W = [‘cat’, mouse’,’dog’,’cat’,rabbit’]

D ---> ‘cat’ ---> 20


‘dog’ ---> 10

Before

Look at each word in W and update D accordingly


Updating a Dictionary

W = [‘cat’, mouse’,’dog’,’cat’,rabbit’]

D ---> ‘cat’ ---> 21


‘dog’ ---> 10

After

Look at each word in W and update D accordingly


Updating a Dictionary

W = [‘cat’,‘mouse’,’dog’,’cat’,’rabbit’]

D ---> ‘cat’ ---> 21


‘dog’ ---> 10

Before

Look at each word in W and update D accordingly


Updating a Dictionary

W = [‘cat’,’mouse’,’dog’,’cat’,’rabbit’]

D ---> ‘cat’ ---> 21


‘dog’ ---> 10
‘mouse’ ---> 1
After

Look at each word in W and update D accordingly


Updating a Dictionary

W = [‘cat’,’mouse’,’dog’,’cat’,’rabbit’]

D ---> ‘cat’ ---> 21


‘dog’ ---> 10
‘mouse’ ---> 1
Before

Look at each word in W and update D accordingly


Updating a Dictionary

W = [‘cat’,’mouse’,’dog’,’cat’,’rabbit’]

D ---> ‘cat’ ---> 21


‘dog’ ---> 11
‘mouse’ ---> 1
After

Look at each word in W and update D accordingly


Updating a Dictionary

W = [‘cat’,’mouse’,’dog’,’cat’,’rabbit’]

D ---> ‘cat’ ---> 21


‘dog’ ---> 11
‘mouse’ ---> 1
Before

Look at each word in W and update D accordingly


Updating a Dictionary

W = [‘cat’,’mouse’,’dog’,’cat’,’rabbit’]

D ---> ‘cat’ ---> 22


‘dog’ ---> 11
‘mouse’ ---> 1
After

Look at each word in W and update D accordingly


Updating a Dictionary

W = [‘cat’,’mouse’,’dog’,’cat’,’rabbit’]

D ---> ‘cat’ ---> 22


‘dog’ ---> 11
‘mouse’ ---> 1
Before

Look at each word in W and update D accordingly


Updating a Dictionary

W = [‘cat’,’mouse’,’dog’,’cat’,’rabbit’]

D ---> ‘cat’ ---> 22


‘dog’ ---> 11
‘mouse’ ---> 1
After ‘rabbit’ ---> 1

Look at each word in W and update D accordingly


Design Two Key
Functions To Do all the Work

stringToWordList(s)

Update(wList,D)
stringToWordList
def stringToWordList(s):
t = ''
for c in s.lower():
alfa = 'abcdefghijklmnopqrstuvwxyz'
if c in alfa:
A word is made up of
t = t + c lower case letters.
else: After the loop, words are
t = t + ' ' separated by blanks in
the string t.
return t.split()
Update(wList,D)

def Update(wList,D):
for w in wList:
z = w.lower()
if z in D:
D[z]+=1 z is in the dictionary. So
increase its frequency count
else:
D[z]=1 z is not in the dictionary. So
add it in with frequency
initialized to 1
A Sample Computation
communicativeness
condescendingly These are all the
conscientiously words in Pride and
disappointments Prejudice that
discontentedness occur only once
disinterestedness
merchantibility
and which have 15
misrepresentation or more Letters.
recommendations
representations Method. Compute the complete
superciliousness word frequency dictionary. Then
superintendence go through it printing a key if its
uncompanionable value is 1 and its length is 15
unenforceability or greater.

You might also like