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

Python Tuples and Dictionaries Guide

Uploaded by

Adab Ishtiaq
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 views86 pages

Python Tuples and Dictionaries Guide

Uploaded by

Adab Ishtiaq
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

Tuples :

Tuples are defined by enclosing the elements in parentheses () and is immutable in


nature.

Example :

t=() --→ empty tuple

t = (5,) --→ tuple containing single element

t = (1, 2, 3) --→ tuple containing elements of same data type

t = (‘a’, 1, 2.5, 2.0+3.5j) --→ tuple containing elements belonging to different


datatype

Note :

t = (1) --→ is an integer not a tuple.

Where as t1 = (3,) --→ is a tuple

Creating a tuple

Creating tuple form an existing sequence

variable_name = tuple(sequence)

here a sequence can be a list,dictionary,set,string and range() function


example

Creating tuple by taking user input

method 1 : variable_name = tuple(input(‘ Input message goes here’) )

method 2 : variable_name = eval(input(‘ Input message goes here’) )

Note the difference between the two in first method the value is passed as string
which is converted into tuple whereas in second method the value is passed in form of
tuple.

Accessing tuple elements

• Elements of tuple can be accessed through indexing

• Syntax : tuple_name[index]

eg tup = (1,’a’,3,4.5)

-4 -3 -2 -1 ←-- backward indexing


1 ‘a’ 3 4.5
0 1 2 3

--→ forward indexing


so,

Traversing a Tuple

Traversing is visiting elements of the tuple.


Tuple operation

• Concatenation
• Replication
• max()
• min()
• count()
• del
• index

Concatenation :

• Join two or more tuples only.


• + operator is used to concatenate the tuples

Syntax : tuple1 + tuple2

Replication :

• It replicates tuple elements


• * operator is used to Replicate the tuples
Syntax : tuple * integer_Literal

Note : tup still remains unchanged

max() and min():

• max() function returns the maximum value


• min() function returns the minimum value

Syntax :

• max(tuple_name)
• min(tuple_name)

index() : The method returns the index value of an item. If item not found then error
is generated

syntax :

tuple_name.index(value)
Note : Here index value of 9 is obtained as it is in the tuple, but for 8 value error is
raised as it is not in the tuple.

del :

used to delete tuple. As tuples are immutable objects one cannot delete individual
elements.

Syntax :

del tuple_name

Note : If you try to use the tuple after using del, NameError will be generated
Note :

del tuple_name[index] #deleting an element at a particular index

or

del tuple_name[start : stop] #deleting a range of elements in tuple

will generate an error as individual or range of elements cannot be deleted in tuples.

count() : It is used to count the occurrence of an element in a tuple

Syntax :

tuple_name.count(value)
Dictionaries

A mutable and unordered collection of key : value pairs enclosed in curly brackets, Where each key :
value pair is separated by comma.

Note:

• Internally dictionaries are indexed by its keys.


• The Keys must be of immutable data type and
• Each key must be unique

{ } → Empty Dictionary
{ 1 : ’a’, 2 : ’b’, 3 : ’c’ }

Creating a dictionary

Syntax:

dictionary_name = { key : value , Key : value, …………}

Example

d = { 1 : ’Hello’, 2 : ‘Bye’, 3 : ‘See You’ }

language = { ‘Python’ : ‘Gudio Van Rossum’, ‘C’ : ‘Dennis Ritchie’, ‘Java’ : ‘James Gosling’, ‘C++’ :
‘Bjarne Stroustrup’}

Accessing elements of dictionary:

Dictionary elements are accessed through leys defined in key : value pair.

Syntax:

dictionary_name[key]

Example

Note: Attempting to access a key that doesn’t exist will cause an error
Traversing a dictionary

Adding and updating an element in a dictionary:

Adding a new key : value pair is done via assignment operation. If a key is already present then its
corresponding value will be updated otherwise a new key : value pair will be added to the dictionary.

Syntax:

dictionary_name[ key ] = value

Example:
Deleting an element from dictionary

deleting an element from dictionary one can be done in two ways

• del statement
• pop(key) method

del statement

Syntax:

del dictionary_name[key] → will delete the specified key : value pair. If the key is not found then an
error will be raised.

del dictionary_name → will delete the entire dictionary

Example:
pop(key) method:

Syntax:

dictionary_name.pop(key) → will delete the specified key value pair and returns it. If the key is not
present an error is raised.
Clearing the contents of dictionary:

clear() method is used to remove all key : value pair in a dictionary. Here an empty dictionary is
obtained after applying the operation.

Syntax:

dictionary_name.clear()

Example:

Obtaining the length of dictionary

len() → returns the length of the dictionary i.e., number of key : value pair it has.

Syntax: len(dictionary_name)

Example:
Getting keys of the dictionary

keys() → This method returns list of keys in a dictionary

syntax: dictionary_name.keys()

Example:

Getting values of the dictionary

values() → This method returns list of values in a dictionary

Syntax: dictionary_name.values()

Example:

Getting key : value pair of the dictionary

items() →This method returns list of (key , value) pair tuple

Syntax: dictionary_name.items()

Example:
Getting a value corresponding to a key

get(key) → This method takes key as an input and returns the corresponding value. If a non-existing
key is passed it returns None

Syntax: dictionary_name.get(key)

Example:

Updating dictionary contents

update() → This method merges key : value pairs from the new dictionary into the existing one. The
item in the new dictionary is added to the old one and overrides any item already there with the
same keys.

Syntax: dictionary_name.update(another_dicitionary_name)

Example:
File handling
 A text file consists of human readable characters, which can be opened by
any text editor. On the other hand, binary files are made up of non-human
readable characters and symbols, which require specific programs to
access its contents
 A file is a named location on a secondary storage media where data are
permanently stored for later access. Mainly there are two types of files
Text and binary.
 A text file consists of human readable character and can be opened in
any text editor. Eg: .py, .txt, .csv etc
 A binary file consists of non-human readable character and symbols and
requires specific programs to access the contents. Eg: audio files, image
files, video files etc.

Steps : working with files


Step 1 : Opening file in python : To open a file in Python, we use the open()
function. The syntax of open() is as follows:
file_object= open(file_name, access_mode)
This function returns a file object called file handle which is stored in the
variable file_object. We can use this variable to transfer data to and from the
file (read and write) by calling the functions defined in the Python’s io module.
Table : Some File-modes

File Meaning File offset position


mode

r Read a [Link] not present an error is Beginning of the file


thrown

w Write mode, If not present a new file is Beginning of the file


created. Otherwise the old one is
overwritten

wb Write a binary file. Beginning of the file

rb Read a binary file Beginning of the file

a Opens the file in append mode. If not End of the file


present then a new file is created

ab Opens the binary file in append mode. End of the file


If not present then a new file is created
Step 2 : Read form or write into the file by using the functions available such as
read(), readline or write(), writelines etc. The syntax is as follows:
file_object.method_name()

Step 3 : After readind or writing is done it is important to close the file. Python
provides a close() method to do so. While closing a file, the system frees the
memory allocated to it. The syntax of close() is:
file_object.close()

Alternatively
one can also open a file using with clause. The syntax of with clause is:
with open (file_name, access_mode) as file_ object:
The rest remains the same. The only advantage here is that the file closes
automatically onces the conrol comes outside the with clause
Example 1 : When using open() method.
Write a program to create a file name [Link] and write the following content
Hello word Let’s learn a thing or two about file handling.

Code :

A file name my_file.txt is created at the loction /home/shaan on successful


execution of the above program.

Output : file named my_file.txt displaying its contents


Example 2 :
considering the same example but now using with clause

Code :

A file name my_newfile.txt is created at the loction /home/shaan on successful


execution of the above program.

Output: file named my_newfile.txt displaying it’s contents

Note :
Observe the above two codes you will notice that when open() method is used
we need to close the file by using the close() method. But this is not the case
when we use with clause to open a file.

Working with text file :


Operations that can be performed :
 read
 write
 append
write operation
Open the file in write mode. If the file is already there then all the contents is
replaced by new one. If the file is not in the directory then a new file is created.
Method used :
 write() ---> To write single line (ref example 1 and 2)
 writelines() ---> To write multiple lines

writelines() method :
Example 3:

Note : you can use objects like string or tuples to store multiple string and then
pass the string object to the writeline method

append() method
is used to append the data at the end of the previous data if an existing file is
opened in append mode. Otherwise a new file is created if not present in the
directory.

Example 4: In our example we have opened an exising file [Link]


(created in example 3) in append mode and have written a new line ‘I am fine
too..!!!
Read operation
It is used to read the contents of a an already existing file by openning in read
mode. If file is not present then an error is generated

Mehod used :
read(n) ---> read all the contents of a file and return a string
readline(n) ---> it is used to read single line in a file. It returns a string
readlines() ---> it is used to read all the lines in a file and returns list of string.

Consider the file [Link] having the following content


Now we will read [Link] file by using the above methods

Note : contents in r is in form of string if read() method is used

Note : contents in r is in form of string if readline() method is used and it reads


only the first line of the text file
Note : It reads all the lines and return list of strings

Binary Files
In order to work with binary file one need to import pickle module first and then
can use dump() or load() method to perform write and read operations
respectively.

Syntax to import pickle module :


import pickle

The dump() method converts the python object to write the data into a binary
file. This process is called pickling. The file in which data is to be dumped is
opened in binary write mode (wb)

Syntax:
[Link](data_object ,file object)
Example : program to write data in binary file
Now if you open this file in any text editor it is non human readable format i.e.
the data is not understandable by us. See what we have entered and how the
data is shown in word file. Definetly not in a way it is written.

The load() method is used to load data from binary file. This process is called
unpickling. The file to be loaded is opened in binary read mode.

Syntax :
data_variable = [Link](file_object)
Example : To read data from binary file [Link]

CSV file (Comma Separated Values)


One of the most common ways to save data in tabular format. It must be saved
with .csv extension.
In order to work with csv file one has to import csv module.
Syntax to import csv module :
import csv
writing data into a CSV file
To write a data in csv file we use writer() function that returns a writer object
which converts the data into deliminated string. After that we can go with
writerow() method to write one row at a time or can use writerows() method
to write multiple rows at one go.

Syntax :
writer_object = [Link](file_object)
writer_object.writerow( single_record_object )
writer_obkect.writerows(multiple_records_object)

Example:

A file com_found.csv is being created having following details as shown in the


figure below

com_found.csv when viewed on text edior


com_found.csv when viewed on spreedsheet

another way of writing data into a csv file

import csv
with open('com_found.csv','w') as csv_w :
data = [[101,'Tim','Apple'],[102,'Bill','Microsoft'],[103,'Mark','Facebook'],
[105,'Elon','Tesla']]
write_data = [Link](csv_w)
write_data.writerows(data)
Reading data from a csv file
To reader a data from a csv file we use reader() function which returns an
iterable reader object which is then iterated using a for loop to print the data
row wise
Syntax :
reader_object = [Link](file_object)
Example : Reading data from com_found.csv file

You might also like