Pythonlearn 09 Dictionaries

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

10/01/21

What is a Collection?
• A collection is nice because we can put more than one value in it
Python Dictionaries and carry them all around in one convenient package

Chapter 9 • We have a bunch of values in a single “variable”

• We do this by having more than one place “in” the variable


Python for Everybody • We have ways of finding the different places in the variable
www.py4e.com

1 2

What is Not a “Collection”? A Story of Two Collections..


Most of our variables have one value in them - when we put a new • List
value in the variable - the old value is overwritten
- A linear collection of values that stay in order
$ python
>>> x = 2
>>> x = 4
>>> print(x) • Dictionary
4
- A “bag” of values, each with its own label

3 4
10/01/21

Dictionaries Dictionaries
• Dictionaries are Python’s most powerful data collection
tissue
calculator • Dictionaries allow us to do fast database-like operations in Python

• Dictionaries have different names in different languages


perfume
- Associative Arrays - Perl / PHP
money
candy - Properties or Map or HashMap - Java

http://en.wikipedia.org/wiki/Associative_array - Property Bag - C# / .Net

5 6

Dictionaries Comparing Lists and Dictionaries


• Lists index their entries >>> purse = dict() Dictionaries are like lists except that they use keys instead of
based on the position in the >>> purse['money'] = 12
numbers to look up values
>>> purse['candy'] = 3
list >>> purse['tissues'] = 75
>>> print(purse) >>> lst = list() >>> ddd = dict()
• Dictionaries are like bags - {'money': 12, 'tissues': 75, 'candy': 3} >>> lst.append(21) >>> ddd['age'] = 21
>>> print(purse['candy']) >>> ddd['course'] = 182
no order 3 >>> lst.append(183)
>>> purse['candy'] = purse['candy'] + 2 >>> print(lst) >>> print(ddd)
>>> print(purse) [21, 183] {'course': 182, 'age': 21}
• So we index the things we {'money': 12, 'tissues': 75, 'candy': 5} >>> ddd['age'] = 23
>>> lst[0] = 23
put in the dictionary with a >>> print(lst) >>> print(ddd)
“lookup tag” [23, 183] {'course': 182, 'age': 23}

7 8
10/01/21

>>> lst = list() List


>>> lst.append(21)
>>> lst.append(183)
>>> print(lst)
Key Value Dictionary Literals (Constants)
[0] 21
[21, 183] lst • Dictionary literals use curly braces and have a list of key : value pairs
>>> lst[0] = 23 [1] 183
>>> print(lst)
[23, 183] • You can make an empty dictionary using empty curly braces

>>> ddd = dict() >>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
Dictionary
>>> ddd['age'] = 21 >>> print(jjj)
>>> ddd['course'] = 182 Key Value {'jan': 100, 'chuck': 1, 'fred': 42}
>>> print(ddd)
>>> ooo = { }
{'course': 182, 'age': 21} ['course'] 182
>>> ddd['age'] = 23 ddd >>> print(ooo)
>>> print(ddd) ['age'] 21 {}
{'course': 182, 'age': 23} >>>

9 10

Most Common Name? Most Common Name?


marquard cwen cwen
zhen marquard zhen
csev
csev zhen
marquard
zhen csev zhen

11 12
10/01/21

Most Common Name? Many Counters with a Dictionary


Key Value
marquard cwen cwen One common use of dictionaries is
counting how often we “see” something

zhen marquard zhen >>> ccc = dict()


>>> ccc['csev'] = 1
csev >>> ccc['cwen'] = 1

csev zhen >>> print(ccc)

marquard {'csev': 1, 'cwen': 1}


>>> ccc['cwen'] = ccc['cwen'] + 1
>>> print(ccc)
zhen csev zhen {'csev': 1, 'cwen': 2}

13 14

Dictionary Tracebacks When We See a New Name


When we encounter a new name, we need to add a new entry in the
• It is an error to reference a key which is not in the dictionary dictionary and if this the second or later time we have seen the name,
we simply add one to the count in the dictionary under that name
• We can use the in operator to see if a key is in the dictionary
counts = dict()
>>> ccc = dict() names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
>>> print(ccc['csev']) for name in names :
if name not in counts: {'csev': 2, 'zqian': 1, 'cwen': 2}
Traceback (most recent call last):
counts[name] = 1
File "<stdin>", line 1, in <module> else :
KeyError: 'csev' counts[name] = counts[name] + 1
>>> 'csev' in ccc print(counts)
False

15 16
10/01/21

The get Method for Dictionaries Simplified Counting with get()


The pattern of checking to see if a We can use get() and provide a default value of zero when the key
if name in counts: is not yet in the dictionary - and then just add one
key is already in a dictionary and x = counts[name]
assuming a default value if the key else :
counts = dict()
is not there is so common that there x = 0
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
is a method called get() that does for name in names :
this for us counts[name] = counts.get(name, 0) + 1
x = counts.get(name, 0) print(counts)

Default value if key does not exist


(and no Traceback). {'csev': 2, 'zqian': 1, 'cwen': 2} {'csev': 2, 'zqian': 1, 'cwen': 2}
Default

17 18

Simplified Counting with get() Counting Words in Text

counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names :
counts[name] = counts.get(name, 0) + 1
print(counts)

http://www.youtube.com/watch?v=EHJ9uYx5L58

19 20
10/01/21

Writing programs (or programming) is a very creative and rewarding activity. You can write
programs for many reasons ranging from making your living to solving a difficult data analysis Counting Pattern
problem to having fun to helping someone else solve a problem. This book assumes that
counts = dict()
everyone needs to know how to program and that once you know how to program, you will figure
print('Enter a line of text:')
out what you want to do with your newfound skills. The general pattern to count the
line = input('')
We are surrounded in our daily lives with computers ranging from laptops to cell phones. We words in a line of text is to split
can think of these computers as our “personal assistants” who can take care of many things on words = line.split() the line into words, then loop
our behalf. The hardware in our current-day computers is essentially built to continuously ask us through the words and use a
the question, “What would you like me to do next?” print('Words:', words) dictionary to track the count of
Our computers are fast and have vast amounts of memory and could be very helpful to us if we each word independently.
only knew the language to speak to explain to the computer what we would like it to do next. If print('Counting...')
we knew this language we could tell the computer to do tasks on our behalf that were repetitive. for word in words:
Interestingly, the kinds of things computers can do best are often the kinds of things that we counts[word] = counts.get(word,0) + 1
humans find boring and mind-numbing. print('Counts', counts)

21 22

python wordcount.py
python wordcount.py counts = dict() Enter a line of text:
Enter a line of text: line = input('Enter a line of text:') the clown ran after the car and the car ran
the clown ran after the car and the car ran into the tent words = line.split()
into the tent and the tent fell down on the
and the tent fell down on the clown and the car
print('Words:', words) clown and the car
Words: ['the', 'clown', 'ran', 'after', 'the', 'car', print('Counting...’)
'and', 'the', 'car', 'ran', 'into', 'the', 'tent', 'and', Words: ['the', 'clown', 'ran', 'after', 'the', 'car',
'the', 'tent', 'fell', 'down', 'on', 'the', 'clown', for word in words: 'and', 'the', 'car', 'ran', 'into', 'the', 'tent', 'and',
'and', 'the', 'car'] counts[word] = counts.get(word,0) + 1 'the', 'tent', 'fell', 'down', 'on', 'the', 'clown',
print('Counts', counts)
Counting… 'and', 'the', 'car']
Counting...
Counts {'and': 3, 'on': 1, 'ran': 2, 'car': 3, 'into': 1,
'after': 1, 'clown': 2, 'down': 1, 'fell': 1, 'the': 7, Counts {'and': 3, 'on': 1, 'ran': 2, 'car': 3,
'tent': 2} 'into': 1, 'after': 1, 'clown': 2, 'down': 1, 'fell':
1, 'the': 7, 'tent': 2}
http://www.flickr.com/photos/71502646@N00/2526007974/

23 24
10/01/21

Definite Loops and Dictionaries Retrieving Lists of Keys and Values


Even though dictionaries are not stored in order, we can write a for
loop that goes through all the entries in a dictionary - actually it >>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
goes through all of the keys in the dictionary and looks up the You can get a list >>> print(list(jjj))
['jan', 'chuck', 'fred']
values of keys, values, or >>> print(jjj.keys())
items (both) from ['jan', 'chuck', 'fred']
>>> counts = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
>>> for key in counts: a dictionary >>> print(jjj.values())
[100, 1, 42]
... print(key, counts[key]) >>> print(jjj.items())
...
[('jan', 100), ('chuck', 1), ('fred', 42)]
jan 100
>>>
chuck 1
fred 42
>>> What is a “tuple”? - coming soon...

25 26

Bonus: Two Iteration Variables!


name = input('Enter file:')
handle = open(name)
python words.py
counts = dict() Enter file: words.txt
• We loop through the for line in handle:
to 16
words = line.split()
key-value pairs in a jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
for word in words:
for aaa,bbb in jjj.items() :
dictionary using *two* print(aaa, bbb) counts[word] = counts.get(word,0) + 1
iteration variables aaa bbb bigcount = None
bigword = None
python words.py
• Each iteration, the first jan 100 [jan] 100 for word,count in counts.items(): Enter file: clown.txt
chuck 1
variable is the key and fred 42 [chuck] 1
if bigcount is None or count > bigcount: the 7
bigword = word
the second variable is bigcount = count
the corresponding [fred] 42
print(bigword, bigcount)
value for the key Using two nested loops

27 28
10/01/21

Summary Acknowledgements / Contributions


These slides are Copyright 2010- Charles R. Severance
...
(www.dr-chuck.com) of the University of Michigan School of
Information and open.umich.edu and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change,
feel free to add your name and organization to the list of
contributors on this page as you republish the materials.

Initial Development: Charles Severance, University of Michigan


School of Information

… Insert new Contributors or translation credits here

29 30

You might also like