Lecture 13
Lecture 13
Spring 2015
Reading assignment:
Chapter 13 of the textbook
Sections 14.1~14.5 in Chapter 14 of the textbook
DICTIONARIES CCE20003
HGU
Given the name of a country(key), how can we know the
medal information of this country(value)?
Use a dictionary!
medals = {}
medals = {“United States”: (46, 29, 29), “China”: (38, 27, 2
3), “Great Britain”:(29, 17, 19), ... , “Australia”: (7, 16, 12)}
>>>medals[“United States”]
(46, 29, 29)
>>>medals[“Rep. of Korea”]
(13, 8, 7)
>>>medals[1]
KeyError: 1
CCE20003
HGU
Creating a dictionary
txt = (“one”, “two”, “three”, “four”, “five”)
num = (1, 2, 3, 4, 5)
dict1 = {}
for i in range(len(txt)):
dict1[txt[i]] = num[i]
print dict1
four 4
one 1
five 5
three 3
two 2
CCE20003
HGU
Converting to a list
stg = “maintain”
m a i n t
1 2 2 2 1
CCE20003
HGU
stg = “maintain”
count = {}
For c in stg:
if c in count:
count[c] += 1
else:
count[c] = 1
print count
line separator
How to get rid of white space?
>>>s.strip(), len(s.strip())
(‘Mercury’, 7)
CCE20003
HGU
f = open(“cce20003/planets.txt”, “r”)
count = 0
in_file = False Apply lower()
for line in f: to
count += 1 line.strip().
if line.strip().lower() == “earth”
in_file = True
break Get out of the
if in_file: loop.
print “Earth is in line”, str(count) + “.”
CCE20003
HGU
Appending a line
………………………
for name, money in lst:
print “%-11s %6d” % (name, money)
2 spaces
left-aligned
CCE20003
HGU
x1 = raw_input(“x1 = “) “60”
x2 = raw_input(“x2 = “) “150”
val = int(x1) + int(x2) 210
print str(val) + “ is “ + x1 + “ + “ + x2
210 is 60 + 150
val x1 x2
print “%d is %s + %s”% (val, x1, x2)
place holders
CCE20003
HGU
Format operators
format string % (arg0, arg1, …..)
Every element in the tuple has its corresponding place ho
lder in the format string.
Place holders
%d integers in decimal
%s strings
%g floats
%f floats
Field width:
>>>”%8.3f %8.3g” % ( 123.456789, 123.456789)
' 123.457 123'
>>>name = “Joseph S. Shin”
>>>amount = 100000
>>>“%20s spent % 10d for shopping.” % (name, amount)
' Joseph S. Shin spent 100000 for shopping.'
>>>“%-20s spent % -10d for shopping.” % (name, amount)
'Joseph S. Shin spent 100000 for shopping.‘
>>>”My name is %-15s .” % name
STRING METHODS CCE20003
HGU
A string is an immutable sequence of characters.
in operator
>>>”abc” in “01234abcdefg”
True
>>>”fgh” in “01234abceefg”
False
A bit different from
the usage for tuples
& lists
CCE20003
HGU
String objects have many useful methods: