UNIT2
UNIT2
Sometimes, it is not enough to only display the data on the console. The
data to be displayed may be very large, and only a limited amount of
data can be displayed on the console since the memory is volatile, it is
impossible to recover the programmatically generated data again and
again.
The file handling plays an important role when the data needs to be
stored permanently into the file. A file is a named location on disk to
store related information. We can access the stored information (non-
volatile) after the program termination.
In Python, files are treated in two modes as text or binary. The file may
be in the text or binary format, and each line of a file is ended with the
special character.
Open a file
Read or write - Performing operation
Close the file
Opening a file
Python provides an open() function that accepts two arguments, file
name and access mode in which the file is accessed. The function returns
a file object which can be used to perform various operations like
reading, writing, etc.
Syntax:
Access
SN Description
mode
It opens the file to read-only mode. The file pointer exists at
1 r the beginning. The file is by default open in this mode if no
access mode is passed.
It opens the file to read-only in binary format. The file
2 rb
pointer exists at the beginning of the file.
It opens the file to read and write both. The file pointer
3 r+
exists at the beginning of the file.
It opens the file to read and write both in binary format. The
4 rb+
file pointer exists at the beginning of the file.
It opens the file to write only. It overwrites the file if
previously exists or creates a new one if no file exists with
5 w
the same name. The file pointer exists at the beginning of
the file.
It opens the file to write only in binary format. It overwrites
6 wb the file if it exists previously or creates a new one if no file
exists. The file pointer exists at the beginning of the file.
7 w+ It opens the file to write and read both. It is different from
Let's look at the simple example to open a file named "file.txt" (stored in
the same directory) in read mode and printing its content on the console.
Example
1. #opens the file file.txt in read mode
2. fileptr = open("file.txt","r")
3.
4. if fileptr:
5. print("file is opened successfully")
Output:
<class '_io.TextIOWrapper'>
file is opened successfully
We can perform any operation on the file externally using the file
system which is the currently opened in Python; hence it is good practice
to close the file once all the operations are done.
Syntax
1. fileobject.close()
After closing the file, we cannot perform any operation in the file. The
file needs to be properly closed. If any exception occurs while
performing some operations in the file then the program terminates
without closing the file.
1. try:
2. fileptr = open("file.txt")
3. # perform file operations
4. finally:
5. fileptr.close()
The syntax to open a file using with the statement is given below.
Example
1. with open("file.txt",'r') as f:
2. content = f.read();
3. print(content)
w: It will overwrite the file if any file exists. The file pointer is at the
beginning of the file.
a: It will append the existing file. The file pointer is at the end of the
file. It creates a new file if no file exists.
Example
1. # open the file.txt in append mode. Create a new file if no such file
exists.
2. fileptr = open("file2.txt", "w")
3.
4. # appending the content to the file
5. fileptr.write('''''Python is the modern day language. It makes things
so simple.
6. It is the fastest-growing programing language''')
7.
8. # closing the opened the file
9. fileptr.close()
Output:
File2.txt
Python is the modern-day language. It makes things so simple. It
is the fastest growing programming language.
We have opened the file in w mode. The file1.txt file doesn't exist, it
created a new file and we have written the content in the file using the
write() function.
Example 2
1. #open the file.txt in write mode.
2. fileptr = open("file2.txt","a")
3.
4. #overwriting the content of the file
5. fileptr.write(" Python has an easy syntax and user-
friendly interaction.")
6.
7. #closing the opened file
8. fileptr.close()
Output:
Python is the modern day language. It makes things so simple.
It is the fastest growing programing language Python has an easy
syntax and user-friendly interaction.
We can see that the content of the file is modified. We have opened the
file in a mode and it appended the content in the existing file2.txt.
To read a file using the Python script, the Python provides the read()
method. The read() method reads a string from the file. It can read the
data in the text as well as a binary format.
Syntax:
1. fileobj.read(<count>)
PREPARED BY : RADADIYA JITENDRA Page 7 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.
Here, the count is the number of bytes to be read from the file starting
from the beginning of the file. If the count is not specified, then it may
read the content of the file until the end.
Example
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","r")
3. #stores all the data of the file into the variable content
4. content = fileptr.read(10)
5. # prints the type of the data stored in the file
6. print(type(content))
7. #prints the content of the file
8. print(content)
9. #closes the opened file
10. fileptr.close()
Output:
<class 'str'>
Python is
In the above code, we have read the content of file2.txt by using the
read() function. We have passed count value as ten which means it will
read the first ten characters from the file.
If we use the following line, then it will print all content of the file.
1. content = fileptr.read()
2. print(content)
Output:
Python is the modern-day language. It makes things so simple.
We can read the file using for loop. Consider the following example.
1. #open the file.txt in read mode. causes an error if no such file exist
s.
2. fileptr = open("file2.txt","r");
3. #running a for loop
4. for i in fileptr:
5. print(i) # i contains each line of the file
Output:
Python is the modern day language.
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","r");
3. #stores all the data of the file into the variable content
PREPARED BY : RADADIYA JITENDRA Page 9 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.
4. content = fileptr.readline()
5. content1 = fileptr.readline()
6. #prints the content of the file
7. print(content)
8. print(content1)
9. #closes the opened file
10. fileptr.close()
Output:
Python is the modern day language.
We called the readline() function two times that's why it read two lines
from the file.
Python provides also the readlines() method which is used for the
reading lines. It returns the list of the lines till the end of file(EOF) is
reached.
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","r");
3.
4. #stores all the data of the file into the variable content
5. content = fileptr.readlines()
6.
7. #prints the content of the file
8. print(content)
9.
10. #closes the opened file
11. fileptr.close()
Output:
x: it creates a new file with the specified name. It causes an error a file
exists with the same name.
a: It creates a new file with the specified name if no such file exists. It
appends the content to the file if the file already exists with the specified
name.
w: It creates a new file with the specified name if no such file exists. It
overwrites the existing file.
Example 1
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","x")
3. print(fileptr)
4. if fileptr:
5. print("File created successfully")
Output:
<_io.TextIOWrapper name='file2.txt' mode='x' encoding='cp1252'>
File created successfully
Output:
The filepointer is at byte : 0
After reading, the filepointer is at: 117
For this purpose, the Python provides us the seek() method which
enables us to modify the file pointer position externally.
Syntax:
PREPARED BY : RADADIYA JITENDRA Page 12 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.
1. <file-ptr>.seek(offset[, from)
offset: It refers to the new position of the file pointer within the file.
from: It indicates the reference position from where the bytes are to be
moved. If it is set to 0, the beginning of the file is used as the reference
position. If it is set to 1, the current position of the file pointer is used as
the reference position. If it is set to 2, the end of the file pointer is used
as the reference position.
Example
1. # open the file file2.txt in read mode
2. fileptr = open("file2.txt","r")
3.
4. #initially the filepointer is at 0
5. print("The filepointer is at byte :",fileptr.tell())
6.
7. #changing the file pointer location to 10.
8. fileptr.seek(10);
9.
10. #tell() returns the location of the fileptr.
11. print("After reading, the filepointer is at:",fileptr.tell())
Output:
The filepointer is at byte : 0
After reading, the filepointer is at: 10
SN Method Description
It closes the opened file. The file once
1 file.close()
closed, it can't be read or write anymore.
2 File.flush() It flushes the internal buffer.
It returns the file descriptor used by the
3 File.fileno() underlying implementation to request I/O
from the OS.
It returns true if the file is connected to a
4 File.isatty()
TTY device, otherwise returns false.
5 File.next() It returns the next line from the file.
6 File.read([size]) It reads the file for the specified size.
It reads one line from the file and places the
7 File.readline([size])
file pointer to the beginning of the new line.
It returns a list containing all the lines of
8 File.readlines([sizehint]) the file. It reads the file until the EOF
occurs using readline() function.
It modifies the position of the file pointer to
9 File.seek(offset[,from) a specified offset with the specified
reference.
It returns the current position of the file
10 File.tell()
pointer within the file.
It truncates the file to the optional specified
11 File.truncate([size])
size.
12 File.write(str) It writes the specified string to a file
13 File.writelines(seq) It writes a sequence of the strings to a file.
Python Strings
String Literals
String literals in python are surrounded by either single quotation marks,
or double quotation marks.
Example
print("Hello")
print('Hello')
Example
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Note: in the result, the line breaks are inserted at the same position as in
the code.
However, Python does not have a character data type, a single character
is simply a string with a length of 1.
Example
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return
a part of the string.
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters from position 5 to position 1 (not included), starting
the count from the end of the string:
b = "Hello, World!"
print(b[-5:-2])
String Length
To get the length of a string, use the len() function.
Example
a = "Hello, World!"
print(len(a))
String Methods
Python has a set of built-in methods that you can use on strings.
strip()
The strip() method removes any whitespace from the beginning or the
end:
lower()
upper()
a = "Hello, World!"
print(a.upper())
replace()
split()
The split() method splits the string into substrings if it finds instances
of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Check String
To check if a certain phrase or character is present in a string, we can
use the keywords in or not in.
Example
Example
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
Example
a = "Hello"
b = "World"
c=a+b
print(c)
Example
String Format
we cannot combine strings and numbers like this:
Example
age = 36
txt = "My name is John, I am " + age
print(txt)
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and
places them in the string where the placeholders {} are:
Example
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
You can use index numbers {0} to be sure the arguments are placed in
the correct placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Escape Character
To insert characters that are illegal in a string, use an escape character.
Example
You will get an error if you use double quotes inside a string that is
surrounded by double quotes:
txt = "We are the so-called "Vikings" from the north."
Example
The escape character allows you to use double quotes when you
normally would not be allowed:
Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
String Methods
Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values. They do not change the
original string.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
Searches the string for a specified value and returns the
find()
position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
Searches the string for a specified value and returns the
index()
position of where it was found
Returns True if all characters in the string are
isalnum()
alphanumeric
Returns True if all characters in the string are in the
isalpha()
alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
PREPARED BY : RADADIYA JITENDRA Page 23 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
Returns a string where a specified value is replaced with a
replace()
specified value
Searches the string for a specified value and returns the
rfind()
last position of where it was found
Searches the string for a specified value and returns the
rindex()
last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
Splits the string at the specified separator, and returns a
rsplit()
list
rstrip() Returns a right trim version of the string
Splits the string at the specified separator, and returns a
split()
list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
Swaps cases, lower case becomes upper case and vice
swapcase()
versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
Fills the string with a specified number of 0 values at the
zfill()
beginning
PREPARED BY : RADADIYA JITENDRA Page 24 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.
Python Lists
A list is a collection which is ordered and changeable. In Python
lists are written with square brackets.
Example
Create a List:
PREPARED BY : RADADIYA JITENDRA Page 25 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.
Access Items
You access the list items by referring to the index number:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Negative Indexing
Negative indexing means beginning from the end, -1 refers to
the last item, -2 refers to the second last item etc.
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Range of Indexes
You can specify a range of indexes by specifying where to start
and where to end the range.
When specifying a range, the return value will be a new list with
the specified items.
Example
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
print(thislist[2:5])
By leaving out the end value, the range will go on to the end of
the list:
Example
This example returns the items from "cherry" and to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
print(thislist[2:])
Specify negative indexes if you want to start the search from the
end of the list:
Example
This example returns the items from index -4 (included) to index
-1 (excluded)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
print(thislist[-4:-1])
Example
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
You will learn more about for loops in our Python For Loops
Chapter.
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Add Items
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Remove Item
There are several methods to remove items from a list:
Example
The remove() method removes the specified item:
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Example
The pop() method removes the specified index, (or the last item
if index is not specified):
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
Example
The del keyword removes the specified index:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
Example
The del keyword can also delete the list completely:
thislist = ["apple", "banana", "cherry"]
del thislist
Example
The clear() method empties the list:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
Copy a List
You cannot copy a list simply by typing list2 = list1,
because: list2 will only be a reference to list1, and changes
made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in
List method copy().
Example
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
Example
Make a copy of a list with the list() method:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
Another way to join two lists are by appending all the items
from list2 into list1, one by one:
Example
Append list2 into list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Example
Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
Add the elements of a list (or any iterable), to the end of the
extend()
current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Tuple
A tuple is a collection which is ordered and unchangeable. In
Python tuples are written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Negative Indexing
Negative indexing means beginning from the end, -1 refers to
the last item, -2 refers to the second last item etc.
Example
Print the last item of the tuple:
Range of Indexes
You can specify a range of indexes by specifying where to start
and where to end the range.
When specifying a range, the return value will be a new tuple
with the specified items.
Example
Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango")
print(thistuple[2:5])
print(x)
You will learn more about for loops in our Python For Loops
Chapter.
Tuple Length
To determine how many items a tuple has, use the len()
method:
Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Add Items
Once a tuple is created, you cannot add items to it. Tuples are
unchangeable.
Example
You cannot add items to a tuple:
thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Remove Items
Note: You cannot remove items in a tuple.
PREPARED BY : RADADIYA JITENDRA Page 40 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
Returns the number of times a specified value occurs in a
count()
tuple
Searches the tuple for a specified value and returns the
index()
position of where it was found
Python Sets
Set
A set is a collection which is unordered and unindexed. In
Python sets are written with curly brackets.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Access Items
You cannot access items in a set by referring to an index, since
sets are unordered the items has no index.
But you can loop through the set items using a for loop, or ask
if a specified value is present in a set, by using the in keyword.
Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Example
Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
Change Items
Once a set is created, you cannot change its items, but you can
add new items.
PREPARED BY : RADADIYA JITENDRA Page 43 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.
Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method.
Example
Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
Example
Add multiple items to a set, using the update() method:
thisset = {"apple", "banana", "cherry"}
print(thisset)
print(len(thisset))
Remove Item
To remove an item in a set, use the remove(), or the discard()
method.
Example
Remove "banana" by using the remove() method:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
Note: If the item to remove does not exist, remove() will raise
an error.
Example
Remove "banana" by using the discard() method:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
Note: If the item to remove does not exist, discard() will NOT
raise an error.
You can also use the pop(), method to remove an item, but this
method will remove the last item. Remember that sets are
unordered, so you will not know what item that gets removed.
The return value of the pop() method is the removed item.
Example
Remove the last item by using the pop() method:
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
Note: Sets are unordered, so when using the pop() method, you
will not know which item that gets removed.
Example
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
Example
PREPARED BY : RADADIYA JITENDRA Page 46 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.
del thisset
print(thisset)
set3 = set1.union(set2)
print(set3)
Example
The update() method inserts the items in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
Set Methods
Python has a set of built-in methods that you can use on sets.
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
PREPARED BY : RADADIYA JITENDRA Page 48 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.
Python Dictionaries
Dictionary
A dictionary is a collection which is unordered, changeable and
indexed. In Python dictionaries are written with curly brackets,
and they have keys and values.
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Accessing Items
You can access the items of a dictionary by referring to its key
name, inside square brackets:
Example
Get the value of the "model" key:
x = thisdict["model"]
There is also a method called get() that will give you the same
result:
Example
Get the value of the "model" key:
x = thisdict.get("model")
Change Values
You can change the value of a specific item by referring to its
key name:
Example
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Example
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
Example
You can also use the values() method to return values of a
dictionary:
for x in thisdict.values():
print(x)
Example
Loop through both keys and values, by using the items()
method:
for x, y in thisdict.items():
print(x, y)
Example
Dictionary Length
To determine how many items (key-value pairs) a dictionary
has, use the len() function.
Example
Print the number of items in the dictionary:
print(len(thisdict))
Adding Items
Adding an item to the dictionary is done by using a new index
key and assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Removing Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key
name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Example
The popitem() method removes the last inserted item (in
versions before 3.7, a random item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
Example
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Example
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer
exists.
Example
The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1,
because: dict2 will only be a reference to dict1, and changes
made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in
Dictionary method copy().
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
Example
Make a copy of a dictionary with the dict() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
Nested Dictionaries
A dictionary can also contain many dictionaries, this is called
nested dictionaries.
Example
Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
Example
Create three dictionaries, then create one dictionary that will
contain the other three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
# note the use of equals rather than colon for the assignment
print(thisdict)
Dictionary Methods
Python has a set of built-in methods that you can use on
dictionaries.
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
Returns the value of the specified key. If the key does not
setdefault()
exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary