Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
113 views

Data Analysis With Python - Day2

name = "Marty"
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
113 views

Data Analysis With Python - Day2

name = "Marty"
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 159

0

Data Analysis with Python:


Zero to Pandas (Day 2)
Waraporn Viyanon

1
Agenda

Day Date Time Topic


1 11 Sept 2021 9.00-10.00 Welcome and Intro to Python

10.00-11.00 Computational Thinking and Programming

11.00-12.00 Function (decomposition) Control Flow: Loops and if statement

2 12 Sept 2021 9.00-10.00 Python Essentials: String, file I/O

10.00-11.00 Python Essentials: Data structure (List, Dictionary)

11.00-12.00 Data Analysis with Python + Example + Python libraries

3 18 Sept 2021 9.00-10.00 Data Analysis with Python: import packages, read data
Data Analysis with Python: clean data, wrangle data, analysis
10.00-11.00
(numerical and categorical data)
11.00-12.00 Data Analysis with Python: data visualization

2
Learning Objectives

• Explain concept of computational thinking


• Code using Python programming
• Analyze data with Python to gain insights from datasets

3
Jupyter Notebook / Colab
Tools for coding

4
Jupyter Notebook

● A Jupyter notebook is a web interface that lets us use formatting alongside our code. It is the
extremely common and very useful!
● You can launch it by typing: Jupyter notebook

5
Jupyter Notebook

● Cells:
○ Markdown for notes
○ Code for Python
● Modes
○ Blue for commands
○ Green for editing
● Execution
○ Shift + return
● Output
○ Print (all)
○ Return values (last)

6
Jupyter Notebook Errors

Mistakes happen! Here’s what they look like:

1. Try to understand what went wrong


2. Attempt to fix the problem
3. Execute the cell again

7
Quick Review: Jupyter Notebook

● Jupyter Notebook interface:


○ Code
○ Mark down

8
Colab

● Colaboratory, or “Colab” for short, is a product from Google Research.


● Colab allows anybody to write and execute arbitrary python code through the browser, and is
especially well suited to machine learning, data analysis and education.
● Colab is a hosted Jupyter notebook service that requires no setup to use, while providing free
access to computing resources including GPUs.

9
Python Essentials

10
Programming and Programming Languages

Programming:

• Writing step-by-step instructions in a way a computer can understand.

Programming Languages

• How we can give computers instructions.


• There are thousands! But we're learning Python.
• Specifically, Python 3

11
Python Indentation

• Indentation refers to the spaces at the beginning of a code line.


• Python uses indentation to indicate a block of code.

12
Image source: https://www.faceprep.in/python/python-indentation/
What we’ve learn from the previous class

13
Variables
and Variable Types
Python Essentials

14
Variables

• Variables are containers for storing data values.

myInt = 4
myReal = 2.5
myChar = "a"
myString = "hello"

15
Creating variables

• Python has no command for declaring a variable.

• A variable is created the moment you first assign a value to it.

x = 5
y = "John"
print(x)
print(y)

5
John

16
Get the Type

• You can get the data type of a variable with the type() function.

x = 5
y = "John"
print(type(x))
print(type(y))

<class 'int'>
<class 'str'>

17
Variable Types

Python has the following data types built-in by default, in these categories:

● Text Type: str


● Numeric Types: int, float
● Sequence Types: list, tuple, range
● Mapping Type: dict
● Set Types: set
● Boolean Type: bool

18
Example

The data type is set when you assign a value to a variable:

Example Data Type

x = "Hello World" str

x = 20 int

x = 20.5 float

x = ["apple", "banana", "cherry"] list


cant amend later
x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = True bool

19
Casting

• If you want to specify the data type of a variable, this can be done with
casting.

x = str(3) # x will be '3'


y = int(3) # y will be 3
z = float(3) # z will be 3.0
print(x)
print(y)
print(z)

3
3
3.0

20
Assign Multiple Values

• Python allows you to assign values to multiple variables in one line

x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y)
print(z)

Orange
Banana
Cherry

Make sure the number of variables matches the number of values, or else you will get an error.

21
Declaring Strings

Let's practice together. Follow along!


1. declare a variable called name and assign it the value Marty
2. declare a variable called car and assign it the value Delorean
3. declare a variable called speed and assign it the string value "88"
4. print out these variables
5. add 4 to speed- what happens?

22
Declaring Strings

• Notice: cannot do math on strings!


• Python sees speed as a string, not a number, so it doesn't know how to do addition on it.
• So, you need to make sure that you want numerical value or string.

23
String Concatenation (+ operator)

● Numerical variables adds (5 + 5 = 10).


● String variables concatenate ("Doc" + "Brown" = "DocBrown").
● Numerical strings concatenate to new strings! ("5" + "4"="54"`)

first_name = "Doc"
last_name = "Brown"
full_name = first_name + last_name

print(full_name) # Prints "DocBrown".

24
Spaces in Concatenation

Let's do this together - follow along!

To begin:

sentence = name + "is driving his" + car + speed

We expect the sentence to be Marty is driving his Delorean 88 mph.

Is that what we got?

25
Strings and Printing: Review

Strings are made with quotes:


name = "Marty"
car = "Delorean"
speed = "88"
String Concatenation - we need to add the spaces!

sentence = name + " is driving his " + car + " " + speed
string_numbers = "88" + "51"
# string_numbers = 8851

To easily create spaces while printing:

print(name, "is driving his", car, speed)

26
Discussion: Some Common Mistakes: 1

● Do you think this will run? If yes, what does it print?

my_num
print(my_num)

27
Discussion: Some Common Mistakes: 2

● How about this? Does it run? If so, what does it print?

my_num = 5
print()

28
Discussion: Some Common Mistakes: 3

● How about this? Does it run? If so, what does it print?

my_num = 5
my_string = "Hello"
print(my_num + my_string)

29
Discussion: Some Common Mistakes: 4

● One last question. What does this do?

my_num1 = "10"
my_num2 = "20"
print(my_num1 + my_num2)

30
Quick Review: Variables

● How to create variables in Python


● Get types of variables
● Casting
● String concatenation (+ operator)
● Print complex structures.

31
String
Python Essentials

32
String

● String is a sequence made up of one or more individual characters that could consist of letters,
numbers, whitespace characters, or symbols.
● Strings in python are surrounded by either single quotation marks, or double quotation marks.
"Hello"

'Hello'
● Assign string to a variable
a = "Hello"
print(a)

a = """This's multi-line string !


You can write anything in triple quotes."""
print(a)

33
String index

● Each of a string’s characters also correspond to an index number,


starting with the index number 0.

S t r i n g s a r e i n d e x e d !

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

● the first S starts at index 0


● the string ends at index 19 with the ! symbol.

34
Accessing Characters by Positive Index Number

● By referencing index numbers, we can isolate one of the characters in a string by putting the index
numbers in square brackets.

S t r i n g s a r e i n d e x e d !

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

myString = "Strings are indexed!"


print(myString[4])

35
Accessing Characters by Negative Index Number

● We can also count backwards from the end of the string, starting at the index number -1.

S t r i n g s a r e i n d e x e d !
-20 -19 -18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

myString = "Strings are indexed!"


print(myString[-3])

36
Slicing Strings

● With slices, we can call multiple character values by creating a range of index numbers separated by
a colon [x:y]:

S t r i n g s a r e i n d e x e d !

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

myString = "Strings are indexed!"


print(myString[12:18])

● the first index number is where the slice starts (inclusive), and the second index number is where the
slice ends (exclusive).

37
Specifying Stride while Slicing Strings

● String slicing can accept a third parameter in addition to two index numbers.
● The third parameter specifies the stride, which refers to how many characters to move forward after
the first character is retrieved from the string.

S t r i n g s a r e i n d e x e d !

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

myString = "Strings are indexed!"


print(myString[1:18:2])

38
Stride to -1

● you can indicate a negative numeric value for the stride, which we can use to print the original string
in reverse order if we set the stride to -1:

S t r i n g s a r e i n d e x e d !

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

myString = "Strings are indexed!"


print(myString[::-1])

39
len() function

● The len() function returns the number of characters in a string.

S t r i n g s a r e i n d e x e d !

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

myString = "Strings are indexed!"


print(len(myString))

40
Discussion: index and len()

● Index starts at index number 0.


● The last index: name = 'John'
last_index is equal to len(name) - 1
J o h n

0 1 2 3
● What happens for this code?

name[len(name)]

41
String concatenation

● Use the + character to add a variable to another variable:

greet = 'Hello, ' greet 'Hello, '


name = 'John'
sentence = greet + name
print(sentence)
name
'John'

sentence 'Hello, John'


42
Quick Review: String

● String is a sequence of one or more characters.


● String index starts with 0.
● len() function returns the length of a string.
● Operator + is used to concatenate strings

43
String Methods
Python Essentials - String

44
String Methods (String functions)

● Python has built-in functions for performing various operations on strings, which can be called in
the following format:

variable.function_name()

45
String Methods

● str.isupper(), str.islower()

● Checks if all Alphabets in a String are Uppercase or Lowercase.


● Returns true or false.

46
isupper(), islower()

text = 'this is all lowercase.'


print(text.isupper())
print(text.islower())
print('***')

text = 'THIS IS ALL UPPERCASE.'


print(text.isupper())
print(text.islower())
print('***')

text = 'This is title-case.'


print(text.isupper())
print(text.islower())
print('***')

47
String Methods

● str.isalpha(), str.isdigit()

● isalpha() checks if All Characters are Alphabets


● isdigit() Checks Digit Characters

48
isalpha(), isdigit()

text = '02-111-2222'
print(text.isdigit())

text = '98765'
print(text.isdigit())

49
String Methods

● str.upper(), str.lower()

● upper() returns uppercased string


● lower() returns lowercased string

50
upper(), lower()

text = 'Welcome to the new world!'


upperText = text.upper()
lowerText = text.lower()

print(text)
print(upperText)
print(lowerText)

51
upper(), lower()

text = 'Hello 123'


upperText = text.upper()
lowerText = text.lower()

print(text)
print(upperText)
print(lowerText)

52
Quick Review: String Methods

● Python has built-in functions for performing various operations on strings


○ isupper(), islower()
○ isalpha(), isdigit()
○ upper(), lower()

53
String Iteration
Python Essentials - String

54
How to Access Each Character in a String?

● Loop to iterate over characters of a string


○ Start from index number 0 to the last character of a string (len(str)-1).

55
Using for Loop to Traverse a String

H e l l o W o r l d !

0 1 2 3 4 5 6 7 8 9 10 11

text = 'Hello World!'


for char in text:
print(char)

56
Using Range to Iterate over a String

H e l l o W o r l d !

0 1 2 3 4 5 6 7 8 9 10 11

text = 'Hello World!'


for i in range(len(text)):
char = text[i]
print(char)

57
Using While Loop to Traverse a String

H e l l o W o r l d !

0 1 2 3 4 5 6 7 8 9 10 11

text = 'Hello World!'


i = 0
while i < len(text):
char = text[i]
print(char)
i = i + 1

58
Quick Review: String Iteration

How to access each character in a string?

● Using for loop to traverse a string:


text = 'Hello World!'
for char in text:
print(char)

● Using range to iterate over a string


text = 'Hello World!'
for i in range(len(text)):
char = text[i]
print(char)
● Using while loop to traverse a string
text = 'Hello World!'
i = 0
while i < len(text):
char = text[i]
print(char)
i = i + 1

59
Data Structures
Python Essentials

60
How to Store the Data?

1. All English letters


2. Exam scores of 70+ students
3. Twitter tagged with #covid19

61
How to Store the Data?

1. All English letters string 26 variables


2. Exam scores of 70+ students float 70+ variables
3. Twitter tagged with #covid19 string xx variables

62
List
Python Essentials – Data Structures

63
List

● A list is a Python Data Structures in Python that is a mutable, or changeable, ordered sequence of
elements.
● Each element or value that is inside of a list is called an item.
● Lists are defined by having values between square brackets [ ].

● Lists are great to use when you want to work with many related values.

64
Create a list

● Put items in a square bracket.

myList = [0, 'Hello World', 3.14]

● Each item splitted with commas

65
List index

● Each item in a list corresponds to an index number, which is an integer value, starting with the index
number 0.

myList = [0, 'Hello World', 3.14]

0 'Hello World' 3.14


myList
0 1 2

66
Access List Elements

● Accessing each item using index.

myList = [0, 'Hello World', 3.14]


print(myList[1])

67
List Length

● list method len() returns the number of elements in the list.

myList = [0, 'Hello World', 3.14]


size = len(myList)
print(size)

68
In Operator

Check if the item is in the list.

myList = [0, 'Hello World', 3.14]


if 0 in myList:
print('Yes')
else:
print('No')

Python's in operator lets you loop through all the members of a collection(such as a list or a tuple) and check if
there's a member in the list that's equal to the given item.

69
In Operator

Check if the item is in the list.

myList = [0, 'Hello World', 3.14]


if '0' in myList:
print('Yes')
else:
print('No')

70
Quick Review: List

● A list is a Python Data Structures in Python that is a mutable, ordered sequence of elements.
● A list can be created using square brackets.
● List index starts at 0.
● Accessing each item using index.
● len() return the size of the list.
● Using the in operator to check if the item is in the list.

71
List Iteration
Python Essentials – Data Structures

72
Loop on List

● Using index (with for or while loops)


● Without index (for loop only)

73
Loop on List (using index)

Start with index number 0 to the last element (len(list)-1)

myList = [0, 'Hello World', 3.14]


for i in range(len(myList)):
element = myList[i]
print(element)

0 'Hello World' 3.14


myList
0 1 2

74
Loop on List (using index)

Start with index number 0 to the last element (len(list)-1)

myList = [0, 'Hello World', 3.14]


for i in range(3):
element = myList[i]
print(element)

0 'Hello World' 3.14


myList
0 1 2
75
Practice

Try to change from for loop to while loop?

76
Loop on List (element-wise)

element
For loop does not need index.

Example.

myList = [1, 3, 5]
for element in myList:
print(element)

1 3 5
myList
0 1 2
77
Loop on List (element-wise)

For loop does not need index.

Example. element

myList = [1, 3, 5]
for element in myList:
print(element)

1 3 5
myList
0 1 2
78
Loop on List (element-wise)

For loop does not need index.

Example.

myList = [1, 3, 5]
for element in myList: element
print(element)

1 3 5
myList
0 1 2
79
Quick Review: List Iteration

● Two ways to loop in the list


○ With Index (for, while)
○ Without Index -- iterate each element in the list (only for loop)

80
List Operations
Python Essentials – Data Structures

81
List Property

You can do these to List:

● Get list size


● Iterate each item in the list
● Check if item is in the list or not

82
List Operations

1. Add element into list


2. Remove element from list
3. Append 2 lists
4. Get index of element in list
5. Use list as parameter (in function)

83
Add Element into List

listA = [0, 'Hello World', 3.14]


0 'Hello 3.14
listA World'
listA.append(-15)
print(listA) 0 1 2

0 'Hello 3.14 -15


listA World'

0 1 2 3

84
Insert Element into List (anywhere)

listA = ['a','c','d']
print(listA)

# list.insert(i, elem)
listA.insert(1,'b')

print(listA) listA ‘a’ ‘c’ ‘d’

85
Insert Element into List (anywhere)

listA = ['a','c','d']
print(listA)

# list.insert(i, elem)
listA.insert(1,'b')

print(listA) listA ‘a’ ‘b’ ‘c’ ‘d’

86
Remove Last Element from List

listA = [0, 5, 3.14]


last = listA.pop()
print(last)
print(listA)

87
Remove Last Element from List

listA = [0, 5, 3.14] listA 0 5 3.14


last = listA.pop()
print(last)
print(listA)

88
Remove Last Element from List

listA = [0, 5, 3.14] listA 0 5 3.14


last = listA.pop()
print(last)
print(listA)

last

89
Remove Last Element from List

listA = [0, 5, 3.14] listA 0 5


last = listA.pop()
print(last)
print(listA)

last

3.14

90
Remove Last Element from List

listA = [0, 5, 3.14]


listA
last = =listA.pop()
[0, 5, 3.14] listA 0 5 len(listA) = 2
last = listA.pop()
print(last)
print(last)
print(listA)

last

91
Remove Element from Anywhere in the List

listA = ['a', 'c', 'd'] 0 1 2


listA
# Remove 'c' from the list
‘a’ ‘c’ ‘d’
removed = listA.pop(1)
print(listA)

removed ‘c’

0 1
listA
‘a’ ‘d’

92
Append 2 Lists

1. Use ‘+’ like string


listA 1 2 3

listA = [1, 2, 3]
listA = listA + [4,5]
print(listA)

listA 1 2 3 4 5

93
Append 2 Lists

2. Use .extend()
listA 1 2 3

listA = [1, 2, 3]
listA.extend([4, 5])
print(listA)

listA 1 2 3 4 5

94
Challenge: + vs Extend

a = [1, 2, 3] a = [1, 2, 3]
b = [4, 5] b = [4, 5]
c = a + b a.extend(b)

After running the code above, what a and b will be?

95
Use List as Parameter

Recap

def add(a, b): x = 1


return a+b y = 5
z = add(x, y)

x=1, y=5 value of x and y remain the same

96
List as Parameters

def listOp(listA): listX = [1]


listA.extend([4, 5]) listOp(listX)

What is listX?

97
List as Parameters

def listOp(listA): listX


listX == [1]
[1]
listA.extend([4, 5]) listOp(listX)
listOp(listX)

listX 1

list A

98
List as Parameters

def listOp(listA):
listOp(listA): listX
listX == [1]
[1]
listA.extend([4,
listA.extend([4, 5])
5]) listOp(listX)
listOp(listX)

listX 1 4 5

list A

99
Caution When Use List as Parameter

● List can be changed

● Understand function that use list as parameter

100
Quick Review: List Operations

● Create a list:
○ Put items in a square bracket
○ Each item splitted with commas myList = [0, 'Hello World', 3.14]
● Print out specific elements in a list for i in range(3):
element = myList[i]
print(element)

● Perform common list operations.


○ Add element into list: append(), insert()
○ Remove element from list: pop()
○ Append 2 lists: + operator, extend()
○ Get index of element in list: listA[1]
○ Use list as parameter (in function)

101
Range
Python Essentials – Data Structures

102
range() function

for i in range(5):
print(i)

103
range() function

Question: print numbers from 5 - 100 that are divided by 5

for i in range(101):
if i >= 5:
if i % 5 == 0:
print(i)

for i in range(5, 101, 5):


print(i)

104
range() function

Question: print numbers from 100 to 1

for i in range(???): for i in range(100, 0, -1):


print(i) print(i)

105
range -> slice

All 3 parameters in range can be use in slice too!

106
Find Reverse String

word = 'camp' word = 'camp'


reverse = '' reverse = word[(len(word)-1):-1:-1]
for i in range(len(word)-1, -1, -1):
reverse += word[i]

word = 'camp'
reverse = word[::-1]

107
Quick Review: Range

● The range() function returns a sequence of numbers, starting from 0 by default,


and increments by 1 (by default), and stops before a specified number.

108
Common Pattern with List
Python Essentials – Data Structures

109
List Operations

110
Common Things We Do with Lists

● Turn a string into a list of words


● Count certain items in a list
● Filter items in a list
● Process items in the list in a sorted order
● Process items in the list from right to left

111
Turn a String(sentence) into a List of String(words)

sentence = "Let’s kill this love"


word_list = sentence.split(' ')
len(word_list)

Let’s kill this love

112
Count Certain Things in a List

score_list = [5, 6, 1, 10, 2]


total_count = 0
for number in score_list:
if number > 4:
total_count += 1

score_list 5 6 1 10 2
print(total_count)

total_count

113
Count Certain Things in a List

total_count = 0
score_list = [5, 6, 1, 10, 2]
for i in range(len(score_list)):
total_count = 0
if score_list[i]> 4:
for number in score_list:
total_count += 1
if number > 4:
print(total_count)
total_count += 1

score_list 5 6 1 10 2
print(total_count)

total_count

114
Filter Things in a List

score_list = [5, 6, 1, 10, 2]


new_list = []
for number in score_list:
if number > 4:
new_list.append(number)

score_list 5 6 1 10 2
print(new_list)

new_list 5 6 10

115
Process Things in a List in the Sorted Order

my_list = [5, 2, 10, 3, 5] my_list 5 2 10 3 5


new_list = sorted(my_list)
for x in new_list:
print(x) new_list 2 3 5 5 10

my_list = [5, 2, 10, 3, 5]


my_list.sort()
for x in my_list: my_list 2 3 5 5 10
print(x)

116
Process things in a list from right to left

sentence = "Let's kill this love"


word_list = sentence.split(' ')
flipped_list = word_list[::-1]
for word in flipped_list:
print(word)

word_list Let’s kill this love

flipped_list love this kill Let’s

117
Quick Review: Common Patterns with List

● Common things to do with lists:


○ Turn a string into a list of words
○ Count certain items in a list
○ Filter items in a list
○ Process items in the list in a sorted order
○ Process items in the list from right to left

118
Dictionary
Python Essentials – Data Structures

119
Introducing Dictionaries

Think about dictionaries — they're filled with words and definitions that are paired together.

Programming has a dictionary object just like this!

● Dictionaries hold keys (words) and values (the definitions).


● In a real dictionary, you can look up a word and find the definition.
● In a Python dictionary, you can look up a key and find the value.

120
Introducing Dictionaries

121
Declaring a Dictionary

Dictionaries in programming are made of key-value pairs.


# Here's the syntax:
name_of_dictionary = {"Key1": "Value", "Key2": "Value", "Key3": "Value"}
print(name_of_dictionary[key_to_look_up])
# Prints the value

# And in action...
my_dictionary = {"Puppy": "Furry, energetic animal", "Pineapple": "Acidic tropical
fruit", "Tea": "Herb-infused drink"}

print(my_dictionary)
# Prints the whole dictionary

print(my_dictionary["Puppy"])
# => Prints Puppy's value: "Furry, energetic animal"

122
Dictionaries and Quick Tips

● The order of keys you see printed may differ from how you entered them. That's fine!
● You can't have the same key twice. Imagine having two "puppies" in a real dictionary! If you
try, the last value will be the one that's kept.
● What's more, printing a key that doesn't exist gives an error.
● Let's create a dictionary together.

123
Dictionary Syntax

What if a value changes? We can reassign a key's value: my_dictionary["Puppy"] = "Cheerful".

What if we have new things to add? It's the same syntax as changing the value, just with a new key:
my_dictionary["Yoga"] = "Peaceful".

● Changing values is case sensitive — be careful not to add a new key!

my_dictionary = {"Puppy": "Furry energetic animal", "Pineapple": "Acidic tropical fruit",


"Tea": "Herb infused drink"}

print(my_dictionary)

124
Quick Review: Dictionaries

Make a dictionary.

● Print a dictionary.
● Print one key's value.
● Change a key's value.
Here's a best practice: Declare your dictionary across multiple lines for readability.
Which is better?
# This works but is not proper style.
my_dictionary = {"Puppy": "Furry, energetic animal", "Pineapple": "Acidic tropical fruit", "Tea":
"Herb-infused drink"}

# Do this instead!
my_dictionary = {
"Puppy": "Furry, energetic animal",
"Pineapple": "Acidic tropical fruit",
"Tea": "Herb-infused drink"
}

125
Dictionary Iteration
Python Essentials – Data Structures

126
Looping through Dictionaries

We can print a dictionary with print(my_dictionary), but, like a list, we can also loop through the
items with a for loop:

my_dictionary = {
"Puppy": "Furry energetic animal",
"Pineapple": "Acidic tropical fruit",
"Tea": "Herb infused drink"
}

for key in my_dictionary:


print(my_dictionary[key])

for key in my_dictionary:


print(key, ":", my_dictionary[key])

127
Other Values

We're almost there! Let's make this more complex.

In a list or a dictionary, anything can be a value.

● This is a good reason to split dictionary declarations over multiple lines!


other_values_in_a_dictionary = {
"CA": {"key1" : "value 1",
"another_key" : "a value",
"Joe" : "Even more dictionary!"
},
"WA": ["Trevor", "Courtney", "Brianna", "Kai"],
"NY": "Just Tatyana"
}
print("Here's a dictionary and list in a dictionary:", other_values_in_a_dictionary)
print("----------")
other_values_in_a_list = [
"a value",
{"key1" : "value 1", "key2" : "value 2"},
["now", "a", "list"]
]
print("Here's a list and dictionary in a list:", other_values_in_a_list)

128
Reverse Lookup

Finding the value from a key is easy: my_dictionary[key]. But, what if you only have the value and want
to find the key?

You task is to write a function, reverse_lookup(), that takes a dictionary and a value and returns the
corresponding key.

For example:
The items() method returns a view object.
state_capitals = { The view object contains the key-value pairs
"Alaska" : "Juneau", of the dictionary, as tuples in a list.
"Colorado" : "Denver",
"Oregon" : "Salem",
"Texas" : "Austin"
} dictionary = {'george': 16, 'amber': 19}
search_age = int(input("Provide age"))
print(reverse_lookup("Denver")) for name, age in dictionary.items():
# Prints Colorado if age == search_age:
print(name)

129
Solution

state_capitals = {
"Alaska" : "Juneau",
"Colorado" : "Denver",
"Oregon" : "Salem",
"Texas" : "Austin"
}

def reverse_lookup(value):
for k, v in state_capitals.items():
if value == v:
return k

print(reverse_lookup("Denver")) # Prints Colorado


130
Quick Review: Dictionary Iteration

● Dictionaries:
○ Are another kind of collection, instead of a list.
○ Use keys to access values, not indices!
○ Should be used instead of lists when:
■ You don't care about the order of the items.
■ You'd prefer more meaningful keys than just index numbers.

my_dictionary = {
"Puppy": "Furry, energetic animal",
"Pineapple": "Acidic tropical fruit",
"Tea": "Herb-infused drink"
}

131
File I/O
Python Essentials

132
Entering data into the program

● Embed data directly into the source code of a program (hard code).

● Get an input from a user using the input() function.

● Read data from a file.

133
File Types

● Human readable file


● Binary file -- content must be interpreted by a program or a hardware processor that understands
in advance exactly how it is formatted.
○ Photo
○ Music
○ Word
○ etc.

134
Quick Review: File I/O

● Data can be inputted into a program by:


○ Hard-code
○ Use the input() function
○ Read data from files
● We can categorize file types into two categories:
○ Text file
○ Binary file

135
Reading a File
Python Essentials - File I/O

136
Reading a File

● Read line by line


● Read the whole file to a string
● Read the whole file to a list

137
Approaches of Reading a File Line by Line

● Before reading a file, you need to open the file using open() function.
● Open() function returns a file object that contains methods and attributes to perform various
operations.

● There are many ways to read a file:


1. use open() function and iterate through the file
2. With statement
3. Open a file in for loop

138
Approach#1: Iterate on File

song_file = open('lyrics.txt')
for line in song_file:
if line != '\n':
print(line)

139
Why Doesn’t Print Two Times?

song_file = open('lyrics.txt')
for line in song_file:
if line != '\n':
print(line)

for line in song_file:


if line != '\n':
print(line)

140
readline()

readline() function reads a line of the file and return it in the form of the string.

song_file = open('lyrics.txt')
first = song_file.readline()
second = song_file.readline()
for line in song_file:
if line != '\n':
print(line)

141
Approach#2: With Statement

with open('lyrics.txt') as
song_file:
for line in song_file:
if line != '\n':
print(line)

142
Approach#3: Open a File in For Loop

for line in
open('lyrics.txt'):
if line != '\n':
print(line)

143
Reading Data from File

● Read line by line


● Read the whole file to a string
● Read the whole file to a list

144
Read the Whole File to a String

The read() method returns the read data in the form of a string.

whole_file = open('lyrics.txt').read()
print(whole_file)

145
Reading Data from File

● Read line by line


● Read the whole file to a string
● Read the whole file to a list

146
Read the Whole File to a List

The readlines() method is used to read all the lines at a single go and then return them as each line a
string element in a list.

lines = open('lyrics.txt').readlines()
print(lines)

['Twinkle twinkle little star\n', 'How I wonder what you are\n', 'Up above the world so high\n',
'Like a diamond in the sky \n', '\n', 'Twinkle twinkle little star\n', 'How I wonder what you are']

147
Quick Review: Reading a File

● There are two types of files that can be handled in python, normal text files and binary files
(written in binary language,0s and 1s).
● before reading a file, open the file using open() function, then...
○ Read line by line
○ Read the whole file to a string
○ Read the whole file to a list

148
Writing to Files
Python Essentials - File I/O

149
Writing to Files Similar to Reading a file

Python write() method writes a string str to the file.

f = open('my_fav_song.txt', mode = 'w')


f.write('Silent night, holy night \n')
f.write('All is calm and all is bright')
f.close()

150
caution#1: mode = 'w'

Default mode is 'r' for reading

f = open('my_fav_song.txt')
f.write('Silent night, holy night \n')
f.write('All is calm and all is bright')
f.close()

151
caution#2: write strings only

Parameter of write() method is string.

f = open('my_math.txt', mode =
'w')
f.write(123456789)
f.close()

152
caution#3: close the file

If you write to a file without closing, the data won’t make it to the target
file.
f = open('my_fav_song.txt', mode = 'w') Silent night, holy night
All is calm and all is bright
f.write('Silent night, holy night \n')
f.write('All is calm and all is bright')

153
caution#3: close the file

If you write to a file without closing, the data won’t make it to the target
file.
f = open('my_fav_song.txt', mode = 'w') Silent night, holy night
All is calm and all is bright
f.write('Silent night, holy night \n')
f.write('All is calm and all is bright')

f.close()

with open('my_fav_song.txt', mode = 'w') as f:


f.write('Silent night, holy night \n')
f.write('All is calm and all is bright')
No need to explicitly close the
opened file, “with statement” takes
care of that.

154
caution#4: \n

with open('my_fav_song.txt', mode = 'w') as f:


f.write('Silent night, holy night')
f.write('All is calm and all is bright')

155
Quick Review: Writing to Files

● Writing to files using write() method.


● Don’t forget to:
○ Define mode = ‘w’
○ Write only strings to files.
○ Close file after you’re done.
○ \n, if needed.

156
Summary

We’ve learned:
• Variables and variable types
• String
• Data structures
• List
• Range
• Dictionary
• File I/O

157
Next
Data Analysis with Python

158
See You

159

You might also like