Python Session 27-28 Module 3-Tuples
Python Session 27-28 Module 3-Tuples
Module 3
• Topic 1: Lists
• Topic 2: Dictionaries
• Topic 3: Tuples
• Topic4: Regular expressions
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
3.3
It is not magic, Python roughly translates the tuple Tuple assignment
assignment syntax to be the following:
>>> m = [ 'have', 'fun' ]
>>> x = m[0]
>>> y = m[1]
>>> x
'have'
>>> y
'fun'
Stylistically when we use a tuple on the left side of the assignment statement, we omit the parentheses, but the following is
an equally valid syntax:
>>> m = [ 'have', 'fun' ]
>>> (x, y) = m
>>> x
'have'
>>> y
'fun'
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
The new list is sorted in ascending alphabetical order by the key value.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
3.5 Multiple
Again, it is in hash key order (i.e., no particular order). assignment withthese
If we combine dictionaries
two techniques, we can print out the contents
of a dictionary sorted by the value stored in each key-value pair. To do this, we first make a list of tuples where each tuple
is (value, key). The items method would give us a list of (key, value) tuples, but this time we want to sort by value, not key.
Once we have constructed the list with the value-key tuples, it is a simple matter to sort the list in reverse order and print
out the new, sorted list.
>>> d = {'a':10, 'b':1, 'c':22}
>>> l = list()
>>> for key, val in d.items() :
... l.append( (val, key) ) ...
>>> l
[(10, 'a'), (22, 'c'), (1, 'b')]
>>> l.sort(reverse=True)
>>> l
[(22, 'c'), (10, 'a'), (1, 'b')]
By carefully constructing the list of tuples to have the value as the first element of each tuple, we can sort the list of tuples
and get our dictionary contents sorted by value.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
Because tuples are hashable and lists are not, if we want to create a composite key to use in a
dictionary we must use a tuple as the key.
We would encounter a composite key if we wanted to create a telephone directory that maps
from last-name, first-name pairs to telephone numbers. Assuming that we have defined the
variables last, first, and number, we could write a dictionary assignment statement as follows:
directory[last,first] = number
The expression in brackets is a tuple. We could use tuple assignment in a for loop to traverse
this dictionary.
for last, first in directory:
print(first, last, directory[last,first])
This loop traverses the keys in directory, which are tuples. It assigns the elements of each
tuple to last and first, then prints the name and corresponding telephone number.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
3.9 Debugging
Lists, dictionaries and tuples are known generically as data structures; in this chapter we
are starting to see compound data structures, like lists of tuples, and dictionaries that
contain tuples as keys and lists as values.
Compound data structures are useful, but they are prone to what I call shape errors; that is,
errors caused when a data structure has the wrong type, size, or composition, or perhaps
you write some code and forget the shape of your data and introduce an error.
For example, if you are expecting a list with one integer and I give you a plain old integer
(not in a list), it won’t work.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
2.7 Exercises
Exercise 1: Revise a previous program as follows: Read and parse the “From” lines and pull
out the addresses from the line. Count the number of messages from each person using a
dictionary.
After all the data has been read, print the person with the most commits by creating a list
of (count, email) tuples from the dictionary. Then sort the list in reverse order and print out
the person who has the most commits.
Sample Line: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Enter a file name: mbox-short.txt
cwen@iupui.edu 5
Enter a file name: mbox.txt
zqian@umich.edu 195
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
2.7 Exercises
Method 1 else:
fname = input('Enter the file name: ') usercounts[word] += 1
fhand=open(fname)
usercounts = dict() lst = list()
for line in fhand: for key, val in list(usercounts.items()):
if line.startswith('From'): lst.append((val, key))
if line.startswith('From:'):continue
words = line.split() lst.sort(reverse=True)
word=words[1] print(lst[0])
if word not in usercounts:
usercounts[word] = 1
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
2.7 Exercises
Method 2 else:
fname = input('Enter the file name: ') usercounts[word] += 1
fhand=open(fname)
usercounts = dict() lst = list()
for line in fhand: for key, val in list(usercounts.items()):
if line.startswith('From'): lst.append((val, key))
if line.startswith('From:'):continue
words = line.split() lst.sort()
word=words[1] print(lst[(len(lst)-1)])
if word not in usercounts:
usercounts[word] = 1
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
2.7 Exercises
Exercise 2: This program counts the distribution of the hour of the day for each of the messages. You can pull the hour from the “From”
line by finding the time string and then splitting that string into parts using the colon character. Once you have accumulated the counts for
each hour, print out the counts, one per line, sorted by hour as shown below.
python timeofday.py
Enter a file name: mbox-short.txt
04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
2.7 Exercises
fname = input('Enter the file name: ') hourcounts[word] = 1
fhand=open(fname) else:
hourcounts = dict() hourcounts[word] += 1
for line in fhand:
if line.startswith('From'): lst = list()
if line.startswith('From:'):continue for key, val in list(hourcounts.items()):
words = line.split() lst.append((key,val))
word=words[5]
colpos=word.find(':') lst.sort()
word=word[0:colpos] for key, val in lst:
if word not in hourcounts: print(key, val)
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
2.7 Exercises
Exercise 3: Write a program that reads a file and prints the letters in decreasing order of
frequency. Your program should convert all the input to lower case and only count the
letters a-z. Your program should not count spaces, digits, punctuation, or anything other
than the letters a-z. Find text samples from several different languages and see how letter
frequency varies between languages. Compare your results with the tables at
https://wikipedia.org/wiki/Letter_frequencies.