0% found this document useful (0 votes)
408 views52 pages

Unit 2-Dictionaries

Dictionaries in Python allow storing and accessing data through unique keys rather than through ordered integers like lists. A dictionary is initialized through curly braces containing key-value pairs separated by commas. Values can be accessed and updated through their keys. Dictionaries are useful for tasks like counting word frequencies by using each word as a key and incrementing its value each time that word appears. The get() method provides a safe way to retrieve a value for a given key with a default if the key is not present.

Uploaded by

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

Unit 2-Dictionaries

Dictionaries in Python allow storing and accessing data through unique keys rather than through ordered integers like lists. A dictionary is initialized through curly braces containing key-value pairs separated by commas. Values can be accessed and updated through their keys. Dictionaries are useful for tasks like counting word frequencies by using each word as a key and incrementing its value each time that word appears. The get() method provides a safe way to retrieve a value for a given key with a default if the key is not present.

Uploaded by

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

Python Dictionaries

What is a Collection?

• A collection is nice because we can put more than one value in


them and carry them all around in one convenient package.

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

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

• We have ways of finding the different places in the variable


What is not a “Collection”
• Most of our variables have one value in them - when we put a
new value in the variable - the old value is over written

$ 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

• A linear collection of values that stay in order

• Dictionary

• A “bag” of values, each with its own label


Dictionaries
tissue
calculator

perfume
money
candy

http://en.wikipedia.org/wiki/Associative_array
Dictionaries
• Dictionaries are Python’s most powerful data collection

• Dictionaries allow us to do fast database-like operations in


Python

• Dictionaries have different names in different languages

• Associative Arrays - Perl / Php

• Properties or Map or HashMap - Java

• Property Bag - C# / .Net


http://en.wikipedia.org/wiki/Associative_array
Dictionaries
• Lists index their entries
>>> purse = dict()
>>> purse['money'] = 12
based on the position in
>>> purse['candy'] = 3
the list
>>> purse['tissues'] = 75
• Dictionaries are like bags >>> print purse
{'money': 12, 'tissues': 75, 'candy': 3}
- no order
>>> print purse['candy']
• So we index the things 3
we put in the dictionary >>> purse['candy'] = purse['candy'] + 2
with a “lookup tag” >>> print purse
{'money': 12, 'tissues': 75, 'candy': 5}
Comparing Lists and
Dictionaries
• Dictionaries are like Lists except that they use keys instead of
numbers to look up values

>>> ddd = dict()


>>> lst = list() >>> ddd['age'] = 21
>>> lst.append(21) >>> ddd['course'] = 182
>>> lst.append(183) >>> print ddd
>>> print lst[21, 183] {'course': 182, 'age': 21}
>>> lst[0] = 23 >>> ddd['age'] = 23
>>> print lst[23, 183] >>> print ddd
{'course': 182, 'age': 23}
>>> lst = list()
>>> lst.append(21) List
>>> lst.append(183) Key Value
>>> print lst
[21, 183] [0] 21
lll
>>> lst[0] = 23 [1] 183
>>> print lst
[23, 183]

>>> ddd = dict()


>>> ddd['age'] = 21 Dictionary
>>> ddd['course'] = 182 Key Value
>>> print ddd
{'course': 182, 'age': 21} ['course'] 183
>>> ddd['age'] = 23
ddd
['age'] 21
>>> print ddd
{'course': 182, 'age': 23}
Dictionary Literals (Constants)
• Dictionary literals use curly braces and have a list of key : value
pairs

• You can make an empty dictionary using empty curly braces

>>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}


>>> print jjj
{'jan': 100, 'chuck': 1, 'fred': 42}
>>> ooo = { }>>> print ooo{}
>>>
Most Common Name?

zhen zhenmarquard cwen


zhen csev
csev
marquard marquard
csev cwen
zhen
zhen
Most Common Name?
Most Common Name?

zhen zhenmarquard cwen


zhen csev
csev
marquard marquard
csev cwen
zhen zhen
Many Counters with a
Dictionary
• One common use of dictionary is
counting how often we “see” Key Value
something
>>> ccc = dict()
>>> ccc['csev'] = 1
>>> ccc['cwen'] = 1
>>> print ccc
{'csev': 1, 'cwen': 1}
>>> ccc['cwen'] = ccc['cwen'] + 1
>>> print ccc
{'csev': 1, 'cwen': 2}
Dictionary Tracebacks
• It is an error to reference a key which is not in the dictionary

• We can use the in operator to see if a key is in the dictionary


>>> ccc = dict()
>>> print ccc['csev']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'csev'
>>> print 'csev' in ccc
False
When we see a new name
• When we encounter a new name, we need to add a new entry in
the 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
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

{'csev': 2, 'zqian': 1, 'cwen': 2


The get method for dictionaries

• This pattern of checking to if name in counts:


x = counts[name]
see if a key is already in a
dictionary and assuming a else :
default value if the key is x=0
not there is so common,
that there is a method x = counts.get(name, 0)
called get() that does this
for us
Default value if key does
not exist (and no {'csev': 2, 'zqian': 1, 'cwen': 2}
Traceback).
Simplified counting with get()
• We can use get() and provide a default value of zero when the
key is not yet in the dictionary - and then just add one

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

>>> counts = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}


>>> for key in counts:
... print key, counts[key]
...
jan 100chuck 1fred 42
>>>
Retrieving lists of Keys and
Values
>>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
>>> print list(jjj)
• You can get a list of keys, ['jan', 'chuck', 'fred']
values or items (both) from >>> print jjj.keys()
a dictionary ['jan', 'chuck', 'fred']
>>> print jjj.values()
[100, 1, 42]
>>> print jjj.items()[('jan', 100), ('chuck', 1)

What is a 'tuple'? - coming soon...


Bonus: Two Iteration Variables!
• We loop through the
>>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
key-value pairs in a
dictionary using *two* >>> for aaa,bbb in jjj.items() :
iteration variables ... print aaa, bbb
...
• Each iteration, the first jan 100
aaa bbb
variable is the key and chuck 1
the the second variable fred 42 [jan] 100
is the corresponding >>>
[chuck] 1
value for the key
[fred] 42
Summary
• What is a collection? • Hashing, and lack of
• Lists versus Dictionaries order

• Dictionary constants • Writing dictionary loops


• The most common word • Sneak peek: tuples
• Using the get() method • Sorting dictionaries
Dictionaries Refreshed
• Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary
without any items is written with just two curly braces, like this: {}.

• 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

• dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

• print ("dict['Name']: ", dict['Name'])

• print ("dict['Age']: ", dict['Age'])


Updating Dictionary
• dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

• dict['Age'] = 8; # update existing entry

• dict['School'] = "DPS School" # Add new entry

• print ("dict['Age']: ", dict['Age'])

• print ("dict['School']: ", dict['School'])

• OUTPUT

• dict['Age']: 8

• dict['School']: DPS School


Delete Dictionary Elements
• dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

• del dict['Name'] # remove entry with key 'Name' dict['Age']:


Traceback (most
• dict.clear() # remove all entries in dict
recent call last):
• del dict # delete entire dictionary File "test.py", line 8,
in <module>
print "dict['Age']: ",
• print ("dict['Age']: ", dict['Age'])
dict['Age'];
TypeError: 'type'
• print ("dict['School']: ", dict['School']) object is
unsubscriptable
Properties of Dictionary Keys
• (a) More than one entry per key is not allowed. This means no duplicate key is
allowed. When duplicate keys are encountered during assignment, the last
assignment wins. For example,

• dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}

• print ("dict['Name']: ", dict['Name'])

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 −

• dict = {['Name']: 'Zara', 'Age': 7}

• print ("dict['Name']: ", dict['Name

OUTPUT

Traceback (most recent call last):

File "test.py", line 3, in <module>

dict = {['Name']: 'Zara', 'Age': 7}

TypeError: list objects are unhashable


Built-in Dictionary Functions and Methods
• S.No.Function & Description 1

• cmp(dict1, dict2) No longer available in Python 3.

• 2 len(dict) Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.

• 3 str(dict) Produces a printable string representation of a dictionary

• 4 type(variable) Returns the type of the passed variable. If passed variable is


dictionary, then it would return a dictionary type.
str
• dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}

• print ("Equivalent String : %s" % str (dict))

• Equivalent String : {'Name': 'Manni', 'Age': 7, 'Class': 'First'}


type
• dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}

• print ("Variable Type : %s" % type (dict))

OUTPUT

Variable Type : <type 'dict'>


Python Methods
• S.No.Method & Description

• 1 dict.clear() Removes all elements of dictionary dict

• 2 dict.copy() Returns a shallow copy of dictionary dict

• 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

• 5 dict.has_key(key) Removed, use the in operation instead.


• 6 dict.items() Returns a list of dict's (key, value) tuple pairs
• 7 dict.keys() Returns list of dictionary dict's keys

• 8 dict.setdefault(key, default = None) Similar to get(), but will set


dict[key] = default if key is not already in dict

• 9 dict.update(dict2) Adds dictionary dict2's key-values pairs to


dict

• 10 dict.values() Returns list of dictionary dict's values


dict.formkeys()
• Syntax

• 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)

• print ("New Dictionary : %s" % str(dict))


OUTPUT
New Dictionary : {'age': None,
'name': None, ‘gender': None}
• dict = dict.fromkeys(seq, 10)
New Dictionary : {'age': 10, 'name':
• print ("New Dictionary : %s" % str(dict)) 10, ‘gender': 10}
get()
Syntax

dict.get(key, default=None)

Parameters

• key − This is the Key to be searched in the dictionary.

• default − This is the Value to be returned in case key does not exist.
• dict = {'Name': 'Zara', 'Age': 27}

• print ("Value : %s" % dict.get('Age'))

• print ("Value : %s" % dict.get(‘Gender', "NA"))

• OUTPUT

• Value : 27

• Value : NA
has_key()
• dict.has_key(key)

• dict = {'Name': 'Zara', 'Age': 7}

• print ("Value : %s" % dict.has_key('Age'))

• print ("Value : %s" % dict.has_key(‘Gender'))

• OUTPUT

• Value : True

• Value : False
items()
• dict = {'Name': 'Zara', 'Age': 7}

• print ("Value : %s" % dict.items())

• Result

• Value : [('Age', 7), ('Name', 'Zara')]


Keys()
• dict = {'Name': 'Zara', 'Age': 7}

• print ("Value : %s" % dict.keys())

• Result

• Value : dict_keys(['Age', 'Name'])


setdefault()
• dict = {'Name': 'Zara', 'Age': 7}

• print ("Value : %s" % dict.setdefault('Age', None))

• print ("Value : %s" % dict.setdefault(' Gender ', None))

• print (dict)

• Value : 7

• Value : None

• {'Name': 'Zara', ‘Gender': None, 'Age': 7}


update
• dict = {'Name': 'Zara', 'Age': 7}

• dict2 = {‘Gender': 'female' }

• dict.update(dict2)

• print ("updated dict : ", dict)

• updated dict : {‘Gender': 'female', 'Age': 7, 'Name': 'Zara'}


values
• #!/usr/bin/python3

• dict = {‘Geneder': 'female', 'Age': 7, 'Name': 'Zara'}

• print ("Values : ", list(dict.values()))

• Values : ['female', 7, 'Zara']

You might also like