1 of 36

CS111 – Fundamentals of CS�Lecture 10�Python III�

2 of 36

Reading for this & last lectures

  1. Python Crash Course (Chapters 1 to 8 and 10)
  2. Share any useful resources you find
  3. https://www.freecodecamp.org/
  4. https://www.w3schools.com/python/default.asp

2

3 of 36

Lecture 10 Outline

  1. Dictionaries
  2. Files
  3. Recursion
  4. Mutable and immutable objects
  5. Tuples

3

4 of 36

Remember

  • Any fool can write code that a computer can understand. Good programmers write code that humans can understand
  • Martin Fowler, 2008.

4

5 of 36

Python 3 Keywords

5

6 of 36

6

7 of 36

1. Dictionaries

  • Dictionaries are a very important data structure in Python
  • A dictionary stores (key, value) pairs in an optimized way.
  • Each key is hashed to an index in the table.
  • It is an instance of a map or hashtable.

8 of 36

1. Dictionaries

  • What dictionaries are
  • The main features
  • How to iterate through a dictionary

9 of 36

1. Dictionaries Are Hastables

0

1

2

3

Key 1

Hash Function

Key 2

Key 0

10 of 36

Python Dictionaries Are Ordered

Key 1

Hash Function

Key 2

Key 0

11 of 36

1. Dictionaries

  • Dictionaries are indexed by key.
  • Keys must be hashable.
  • The hash for a key is unique.
  • Values can be of any type

12 of 36

Building a Dictionary

marks = {'Ali': 30, 'Sami': 35}

print (marks)

marks ['Mai'] = 39

print (marks)

marks ['Ali'] = 32

print (marks['Ali'])

del marks ['Ali']

13 of 36

Building a Dictionary

marks = {

'Ali': 30,

'Sami': 35,

'Mai': 28

}

marks

14 of 36

Building a Dictionary

marks = {

'Ali': 30,

'Sami': 35,

'Mai': 28,

'Ali': 20 # Change Ali’s age

}

marks

15 of 36

All Functions of a Dictionary

>> dir (int) # All functions of int

>> dir ({}) # Dictionary func

['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

16 of 36

List vs. Dictionary

  • List
    • Items are ordered
    • Access by index O(1)
    • Insert or delete O(n)
    • No access by key (Loop and search for key)
    • Allows duplication
  • Dictionaries
    • Items are ordered in Python implementation
    • No access by index
    • Access by key, insert or delete O(1)
    • No duplication

17 of 36

Iterating over Dictionary #1

marks = {

'Ali': 30,

'Sami': 35,

'Amina ': 28,

'Aliaa': 20

}

print (marks)

for key, value in marks.items():

if (key[0].upper() == 'A'):

print (key, ' ', value)

17

18 of 36

Iterating over Dictionary #2

marks = {

'Ali': 30,

'Sami': 35,

'Amina ': 28,

'Aliaa': 20

}

print (marks)

for key in marks.keys():

print(key, ' ', marks[key])

18

19 of 36

Iterating over Dictionary #3

marks = {

'Ali': 30,

'Sami': 35,

'Amina ': 28,

'Aliaa': 20

}

print (marks)

for key in marks:

print(key, '->', marks[key])

19

20 of 36

What is really happening?

marks = {

'Ali': 30,

'Sami': 35,

'Amina ': 28,

'Aliaa': 20

}

itr = marks.__iter__()

while itr.__length_hint__() > 0:

key = itr.__next__()

print(key, '->', marks[key])

20

21 of 36

Iterating over Dictionary #4

marks = {

'Ali': 30,

'Sami': 35,

'Amina ': 28,

'Aliaa': 20

}

print (marks)

sum = 0

for value in marks.values():

sum += value

print(sum / len(marks))

21

22 of 36

Deleting Dictionary Items

marks = {

'Ali': 30,

'Sami': 35,

'Amina ': 28,

'Aliaa': 20

}

print (marks)

del marks['Sami']

print (marks)

22

23 of 36

Accessing Dictionary Items

marks = {

'Ali': 30,

'Sami': 35,

'Amina ': 28,

'Aliaa': 20

}

print (marks['Ali'])

print (marks['Amir']) #Error

print (marks.get('Ali'))

print (marks.get('Amir')) #None

marks.get('Amir', 'No Such Key')

23

24 of 36

24

25 of 36

2. Files

  • We cannot input data every time
  • Files are the permanent way to store data for future use.
  • Actual file management on disk is handled by operating system.
  • Main file operations
    1. Open a file
    2. Read or write (perform operation)
    3. Close the file

26 of 36

Reading from Files

# Open existing file for reading

file = open("test.txt")

f = open("C:/Python38/readme.txt")

26

27 of 36

27

Mode

Description

r

Opens a file for reading. (default)

w

Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists.

x

Opens a file for exclusive creation. If the file already exists, the operation fails.

a

Opens a file for appending at the end of the file without truncating it. Creates a new file if it does not exist.

28 of 36

Opening Files

# equivalent to 'r' or 'rt'

f = open("test.txt")

# write in text mode

f = open("test.txt",'w')

# read and write in binary mode

f = open("img.bmp",'r+b')

28

29 of 36

Reading from Files

  • Default encoding is platform dependent. In windows, it is cp1252 (like ASCII) but utf-8 in Linux.
  • If not ASCII, specify which one it is:
  • f = open("test.txt", encoding='utf-8') f = open("test.txt", encoding='utf-16')

  • If not, program will behave different on different systems.

29

30 of 36

Reading from Files

  • f = open("test.txt", encoding = 'utf-8')
  • f.read(4) # read the first 4 data
  • f.read() # read in the rest of file
  • f.read() # returns empty string
  • f.seek(0) # returns cursor to start
  • f.tell() # returns cursor position

30

31 of 36

Reading from Files

  • f = open("test.txt", encoding = 'utf-8')
  • for line in f:

print(line, end = '')

  • f.seek(0)
  • for line in f:
  • print (line.split(), end = '')

  • f.readline()

31

32 of 36

Writing to File

  • ??
  • ??
  • ??
  • Search about it

32

33 of 36

Closing a File

  • When finished, close the file
  • This frees the memory resources used for it

  • file = open('file_path', 'w')
  • file.write('hello world !')
  • file.close()

  • # Auto close
  • with open('file_path', 'w') as file:
  •     file.write('hello world !')

33

34 of 36

Exercise #1

  • Modify hangman game to read words from a file.

35 of 36

Homework …..

  • Read chapters 1 to 8 and 10
  • Work on assignment 3
  • Prepare for Quiz 2

35

36 of 36

Readings

  • Readings are essential for this course. You must read related chapters from

36