HKU - 7001 - 2. More On Python
HKU - 7001 - 2. More On Python
>>> fruit = 'Banana' >>> lotto = [2, 14, 26, 41, 63]
>>> fruit[0] = 'b' >>> print(lotto)
Traceback [2, 14, 26, 41, 63]
TypeError: 'str' object does not >>> lotto[2] = 28
support item assignment >>> print(lotto)
>>> x = fruit.lower() [2, 14, 28, 41, 63]
>>> print(x)
banana
Length of a list
• The len() function takes a list as a parameter and returns
the number of elements in the list
• Actually len() tells us the number of elements of any set
or sequence (such as a string...)
for i in range(len(friends)):
friend = friends[i]
print('Happy New Year:', friend)
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6]
>>> print(a)
[1, 2, 3]
List slicing
• List can be sliced just like strings, but remember, the second
number is “up to but not including”
>>> x = list()
>>> type(x)
<type 'list'>
>>> dir(x)
['append', 'count', 'extend', 'index',
'insert', 'pop', 'remove', 'reverse', 'sort']
Building a List from Scratch
• We can create an empty list and then add elements using
the append method, or extend method.
• The list stays in order and new elements are added at the
end of the list
'uno'
>>> print(eng2sp)
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
Dictionaries
• Dictionaries are like lists except that they use keys instead of
index numbers to look up or add key-value pairs
We can change
the value of a key
Dictionary Tracebacks
• It is an error to reference a key which is not in the dictionary
>>> ccc = dict()
>>> print(ccc['csev'])
Traceback (most recent call last):
File "<stdin>", line 1, in
<module>
KeyError: 'csev'
if name in counts:
x = counts[name]
x = counts.get(name, 0)
else:
x = 0
word = 'brontosaurus'
counts = dict()
for c in word:
counts[c] = counts.get(c,0) + 1
print(counts)
Counting Words in Text
• The general pattern to count the words in a line of text is to
split the line into words, then loop through the words and
use a dictionary to track the count of each word
independently.
line = input('')
line = line.lower()
words = line.split()
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
counts = dict()
for word in text:
counts[word] = counts.get(word,0) + 1
print('Counts', counts)
jan 100
chuck 1
fred 42
Looping through Keys in Order
• Recall: items (key-value pairs) in a dictionary are un-
ordered, i.e., you never get the items from a dictionary in
any predictable order. However, this is not a problem:
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python'}
jan 100
chuck 1
fred 42
Removing Key-Value Pairs
• When we no longer need a piece of information that’s
stored in a dictionary, we can use the del statement
completely remove a key-value pair.
people = {
1: {'Name': 'John', 'Age': '27', 'Sex': 'Male'},
2: {'Name': 'Marie', 'Age': '22', 'Sex': 'Female'}
}
John
Marie
Summary
• Dictionary as a set of counters
• Dictionaries Methods get
• Counting Words in Text
• Looping through Keys in Order
• Removing Key-Value Pairs
• Lists in a dictionary
• Dictionaries in a dictionary
Exercise 2
• Write a program to print a dictionary where the keys are
numbers between 1 and 10 (both included) and the values
are square of keys.
Exercise 3
• Write a program to extract and list all the mayors in the
following dictionary.
fav_city= {
'New York': {'Country': 'USA', 'Population': 8.5, 'Mayor': 'de Blasio'},
'Paris': {'Country': 'France', 'Population': 2.2, 'Mayor': 'Hidalgo'},
'Tokyo': {'Country': 'Japan', 'Population': 9.3, 'Mayor': 'Koike'}
}
• So result should be
>>> x = (3, 2, 1)
>>> x.sort()
Traceback:
AttributeError: 'tuple' object has no attribute 'sort'
>>> x.append(5)
Traceback:
AttributeError: 'tuple' object has no attribute 'append'
>>> x.reverse()
Traceback:
AttributeError: 'tuple' object has no attribute 'reverse'
>>>
A Tale of Two Sequences
• Although list and tuple look alike, they are very different.
>>> l = list()
>>> dir(l)
['append', 'count', 'extend', 'index', 'insert', 'pop',
'remove', 'reverse', 'sort']
>>> t = tuple()
>>> dir(t)
['count', 'index']
Tuples are More Efficient
• Since Python tuple structures are immutable, they are
simpler and more efficient in terms of memory use and
performance than lists
• So in our program when we are making “temporary
variables” we prefer tuples over lists
Tuples and Assignment
• We can also put a tuple on the left-hand side of an
assignment statement
• We can even omit the parentheses
>>> print(tmp)
[(10, 'a'), (22, 'c'), (1, 'b')]
>>> tmp = sorted(tmp, reverse=True)
>>> print(tmp)
[(22, 'c'), (10, 'a'), (1, 'b')]
Even Shorter Version