Unit 2-Dictionaries
Unit 2-Dictionaries
What is a Collection?
$ python
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
>>> x = 2
>>> x = 4
>>> print x
4
A Story of Two Collections..
• List
• Dictionary
perfume
money
candy
http://en.wikipedia.org/wiki/Associative_array
Dictionaries
• Dictionaries are Python’s most powerful data collection
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names :
counts[name] = counts.get(name, 0) + 1
print counts
Default
{'csev': 2, 'zqian': 1, 'cwen': 2}
Simplified counting with get()
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
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 problem to having fun to helping someone else
solve a problem. This book assumes that everyone needs to know how to
program and that once you know how to program, you will figure out what you
want to do with your newfound skills.
We are surrounded in our daily lives with computers ranging from laptops to cell
phones. We can think of these computers as our ``personal assistants'' who
can take care of many things on our behalf. The hardware in our current-day
computers is essentially built to continuously ask us the question, ``What would
you like me to do next?''.
Our computers are fast and have vasts amounts of memory and could be very
helpful to us if we only knew the language to speak to explain to the computer
what we would like it to ``do next''. If we knew this language we could tell the
computer to do tasks on our behalf that were reptitive. Interestingly, the kinds of
things computers can do best are often the kinds of things that we humans find
boring and mind-numbing.
the clown ran after the car and the car ran into the tent and
the tent fell down on the clown and the car
Counting Pattern
counts = dict() The general pattern to count the
print 'Enter a line of text: words in a line of text is to split
'line = raw_input('')
the line into words, then loop
words = line.split() thrugh the words and use a
dictionary to track the count of
print 'Words:', words each word independently.
print 'Counting...’
for word in words:
counts[word] = counts.get(word,0) + 1
print 'Counts', counts
Counting Words
python wordcount.py Enter a line of text:the clown
ran after the car and the car ran into the tent and
the tent fell down on the clown and the car
Words: ['the', 'clown', 'ran', 'after', 'the', 'car', 'and',
'the', 'car', 'ran', 'into', 'the', 'tent', 'and', 'the', 'tent',
'fell', 'down', 'on', 'the', 'clown', '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, 'tent':
2}
http://www.flickr.com/photos/71502646@N00/2526007974/
python wordcount.py
Enter a line of text:the clown ran after
the car and the car ran into the tent
counts = dict() and the tent fell down on the clown
print 'Enter a line of text: and the car
'line = raw_input('')
words = line.split()
Words: ['the', 'clown', 'ran', 'after',
print 'Words:', words 'the', 'car', 'and', 'the', 'car', 'ran', 'into',
print 'Counting...’ 'the', 'tent', 'and', 'the', 'tent', 'fell',
for word in words: 'down', 'on', 'the', 'clown', 'and', 'the',
counts[word] = counts.get(word,0) + 1 'car']Counting...
print 'Counts', counts
Counts {'and': 3, 'on': 1, 'ran': 2, 'car':
3, 'into': 1, 'after': 1, 'clown': 2, 'down':
1, 'fell': 1, 'the': 7, 'tent': 2}
Definite Loops and Dictionaries
• 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 goes through all of the keys in the dictionary and looks up the
values
• Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type such
as strings, numbers, or tuples.
Accessing Values in
Dictionary
• #!/usr/bin/python3
• OUTPUT
• dict['Age']: 8
OUTPUT
• dict['Name']: Manni
• (b) Keys must be immutable. This means you can use strings, numbers or tuples as dictionary
keys but something like ['key'] is not allowed. Following is a simple example −
OUTPUT
• 2 len(dict) Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.
OUTPUT
• 3 dict.fromkeys() Create a new dictionary with keys from seq and values set to
value.
• 4 dict.get(key, default=None) For key key, returns value or default if key not
in dictionary
• dict.fromkeys(seq[, value]))
• Parameters
• seq − This is the list of values which would be used for dictionary keys preparation.
• value − This is optional, if provided then value would be set to this value
• seq = ('name', 'age', ‘gender')
• dict = dict.fromkeys(seq)
dict.get(key, default=None)
Parameters
• default − This is the Value to be returned in case key does not exist.
• dict = {'Name': 'Zara', 'Age': 27}
• OUTPUT
• Value : 27
• Value : NA
has_key()
• dict.has_key(key)
• OUTPUT
• Value : True
• Value : False
items()
• dict = {'Name': 'Zara', 'Age': 7}
• Result
• Result
• print (dict)
• Value : 7
• Value : None
• dict.update(dict2)