0% found this document useful (0 votes)
11 views87 pages

Dictionaries

Uploaded by

adilkhalili9999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views87 pages

Dictionaries

Uploaded by

adilkhalili9999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

Select Topics in Python

Creating and Using Dictionaries


Objectives

Objectives
• Introduction to dictionaries in
Python.
• Initializing dictionaries.
• Manipulating dictionaries.
• Using a list or dictionary for a
program.
Introduction to Dictionaries

| A dictionary
is a set of 'keys' (words)
all pointing to their own 'values'
(meanings).
dict1 = {"first_name" : ”Mike", "last_name" : ”Smith"}

Dictionary name Key 1 Value 1 Key 2 Value 2


String String String String

dict1['John'] = 'Leo'

Dictionary Key 1 Value 1


name String String
Initialize Dictionaries

| Create Dictionary
- Create a default.
- Use a list of key and pair values.
- Make a parallel list.
- dictionary3 = zip(names, degrees)
Dictionary Operations

| Dictionary
- Access values.
- Update.
- Delete.
Dictionary Functions and Methods

| Functions and methods


- len(dictionary)
- str(dictionary)
- type(var)
- dictionary.clear()
- dictionary.deepcopy()
- dictionary.get(key,default=None)
- dictionary.items()
- dictionary.values()
- dictionary.keys()
- dictionary.update(dictionary2)
- dictionary.setdefault(key,
default=None)
Using a List or Dictionary for a program

| When to use a dictionary?


- You don't need things to be in order.
- You can add and remove elements and their
keys.
- If you need it in order, you have to use a list for
that.
Select Topics in Python
Errors and Exceptions
Objectives

Objectives:
• Discover the types of errors.
• Use exceptions.
Types of Error

| Errors
- Syntax error.
- Semantics error.
- Run time error.
- Logical error.
Types of Error

| Syntax error
- Syntax errors: refers to formal rules governing the
construction of valid statements in a language.
- Syntax errors occur when rules of a programming
language are misused, i.e., when a grammatical rule of
the language is violated.
Types of Error

| Semantics errors
- Semantics errors occur when statements are not meaningful.
- Semantics refers to the set of rules which give the meaning of the
statement.
- Examples:
• Jon is registered for a class.
• It is semantically and syntactically correct.
• Class registered a class for Jon.
• Incorrect and not Semantically correct.
Types of Error

| Run time errors


- A run time error occurs during the execution of a program.
It is caused when an illegal operation has taken place.
- As an example:
• Open/write to a file.
• Divide by zero.
Types of Error

| Logical errors
- A logical error causes a program to produce an
incorrect or undesired output.
- As an example:
• Infinite loops
• Mathematical operation.
Exceptions

| What is an exception?
- Even when a statement or
expression is syntactically correct,
it may cause an error when an
attempt is made to execute it.
- An error during this process is
called an exception.
Handling Exceptions

| It is possible to write programs


that handle selected exceptions.
Look at the following example,
which asks the user for input
until a valid integer has been
entered, but allows the user to
interrupt the program using
Control-C or whatever the
operating system supports. Note
that a user-generated
interruption is signalled by
raising the KeyboardInterrupt
exception.
Exception Clause with No Excepptions

| This kind of a try-except


statement catches all the
exceptions that occur. Using this
kind of try-catch statement is not
considered a good programming
practice, because but catches all
exceptions butt doesn’t make the
programmer identify the root
cause of the problem that
occurred.
Common Exceptions

| IOError
- Raised when the file cannot be opened.

| ImportError
- Raised when Python cannot find the module.

| ValueError
- Raised when a built-in operation or function received an argument that has the right
type but an inappropriate value.

| KeyboardInterrupt
- Raised when the user hits the interrupt key.

| EOFError
- Raised when one of the built-in functions(input() or raw_input()) hits an end-of-file
without reading data.
Reading File

| Errors
Write File

| Errors
Select Topics in Python
Creating and Using Lists
Objectives

Objectives:
• Introduction to Lists in Python
• Initialize List
• Add to List
• Calls to List
• Sort or Reverse a List
• Operations on a List
• Slice a List
• Display a List
Introduction to Lists

| Lists Creating a List

- Lists contain items separated by


commas and enclosed within yearBorn = [“Bob Hope”, 1903]
square brackets.
- The values stored in a list can be
accessed using the slice operator (
[ ] and [ : ] )
list name first element: second element:
a string an integer

0 1 2 3 4

Indexing a List
Create and Add to a List

| Create
- Define a variable name.
- Insert items into the list.

| Add to a list
- Insert.
- Extend.
- Append.
- Concatenate ‘+’
Calls to List

| Making calls to a list


Sort a List

| Sort a list
Operations on a List

| Operations
- Index.
- Count.
- Remove.
- Slice.
Display a List

| Display the list


Demo

| Demo
Selected Topics in Python
Using Matplotlib
Objectives

Objectives
• Discover how to use
Matplotlib?
• Explore the different types of
plots
Matplotlib

| What is Matplotlib?
Line Plot

| Line plots
- Used to show trends.
- Compare multiple values.
- Changes of values over time.
- Numerical data.
- Make predictions.
Line Plot

| Line plots
- linestyles
- linewidth
- color
- legend
Bar Plot

| Bar plots
- Normal and/or ordinal
categories.
- Compare data against different
categories.
- Use when greater than 3.
- Compare large data sets over
time.
Scatter Plot

| Scatter plots
- Visualize the relationship between
multiple numerical values.
- Visualize the correlation in a large
data set.
- Predict behavior based on the
measurement of the independent
variable.
Box Plot

| Box plots
- Show whisker plots.
- Displays statistical graph for sets
of numerical data.
- Shows the range, spread and
center.
- Used to compare data from
different categories.
Histograms

| Histograms
- Used for continuous data.
- Displays the frequency distribution.
- Summarizes large data sets
graphically.
- Compare multiple distributions.
Select Topics in Python
Using NumPy
Objectives

Objectives
• Introduction to NumPy.
• Arrays.
• NumPy operations.
Introduction of NumPy

| Importing NumPy
- https://numpy.org/install/
Create Array using NumPy

| Arrays
- Single-dimensional array.
- Multidimensional array.
NumPy Operations

| Operations
- ndim
- itemsize
- dtype
- reshape
- slicing
- linspace
- max
- min
- sum
NumPy Operations (continued)

| Operations
- Square root.
- Standard deviation.
- Math operators.
- Ravel.
NumPy Operations (continued)

| Special functions
- sin(), cos(), tan()
- Exponential
- Log
Selected Topics in Python
Using Pandas
Objectives

Objectives
• What is Pandas?
• Slicing data frame.
• Concatenation.
• Change index.
• Change headers.
• Merging and joining.
What is Pandas?

| Preform data operations


- Series.
- Data frames.
- Missing data.
- Group data.
Slicing Data Frame

| Slice
- Show all.
- Show number of rows from head.
- Show number of rows from tail.
Change Index

| Set index
Change Headers

| Modify header name


Merging and Joining

| Merge and join data


Select Topics in Python
Reading from File
Objectives

Objectives
• Introduction file I/O.
• Loading a file in Colab.
• Reading from a file.
• String splitting.
Introduction File I/O

| I/O
- Why do we need to use I/O?
• Storing data.
• Accessing data.
• Modifying data.
Loading a File in CoLab

| Loading file
- Select folder.
- Open sample_data.
- Select three dots.
- Upload.
Reading From a File

| Read files readFile = open(FILE_NAME [, ACCESS_MODE])


- Open file.
- Read file.
• read
• readline
• readlines
String Splitting

| String Splitting
- Split default.
- Split by character.
- Split by characters.
- Split using for loop.
Select Topics in Python
Creating and Using Sets
Objectives

Objectives
• Introduction sets.
• Implementation of sets.
• Using range function.
• Iterate through a set.
• Set operations.
• Set functions.
Introduction Sets

| Sets
- Unordered collection.
• Iterable.
• Mutable.
• No duplications.
• Also know as a hash table.
Implementation of a Set

| Set
- Empty set.
- Defined set.
- Set method.
Using the Range Function

| Range
- Using 1, 2, and/or 3 consists.
Iterate Through a Set

| Iteration
- For loop.
Set Operations

| Sets are mutable


- add()
- update()
- pop()
- remove()
- clear()
Set Operations (continued)

| Sets are mutable


- union()
- intersection()
- difference()
- isdisjoint()
- issubset()
- issuperset()
- discard()
- copy()
Function in Sets

| Function
- len()
- max()
- min()
- sorted()
- sum()
Select Topics in Python
Creating and Using Tuples
Objectives

Objectives
• Introduction to tuples in Python
• Initialize tuples
• Convert to tuples
• Slice to tuples
• Iterate through a list of tuples
Introduction to Tuples

| Tuples.
- Data structure in Python.

| Each value in the tuple yearBorn = (”Bob Hope", 1903)


is an element or item.

| Elements can be any


Python data type. tuple name first element: second element:
a string an integer
- Tuples can mix data types.
- Elements can be nested tuples.

In Python, a tuple is an immutable sequence of values.


Initialize Tuples

| Create a tuple
- Empty set.
- Lists.
- Comparison string and tuples.
- Splice of a string.
Converting to Tuples

| Convert to Tuple
- List to tuple.
• Tuple function.
• For loop.
• Unpack list.
Slicing to Tuples

| Slicing
Iterating Through List of Tuples

| Iterations
- For loop.
- Enumerate.
Selected Topics in Python
Writing to a File
Objectives

Objectives
• Writing to a File
Writing to a File

| Write to a file
- Open.
- Write.
• w vs. a
- Close.

You might also like