Lecture 5 Python Self notes
Lecture 5 Python Self notes
Python3 programming
Lecture 5
Dictionary
❑Dictionaries are used to store data values in
key:value pairs.
❑A dictionary is a collection which is ordered*,
changeable and do not allow duplicates.
❑Each key is separated from its value by a colon
(:), the items are separated by commas, and the
whole thing is enclosed in curly braces.
❑ An empty dictionary without any items is
written with just two curly braces, like this: {}.
❑Keys are unique within a dictionary while
values may not be.
❑The values of a dictionary can be of any type,
but the keys must be of an immutable data type
such as strings, numbers, or tuples.
Updating
Dictionary
❑ We can update a
dictionary by adding a
new entry or a key-value
pair, modifying an existing
entry, or deleting an
existing entry as shown in
a simple example given
below.
Delete
Dictionary
Elements
Sets
❑ access_mode : The access_mode determines the mode in which the file has to be
opened, i.e., read, write, append, etc. A complete list of possible values is given
below in the table. This is optional parameter and the default file access mode is
read (r).
Mode Description
r Opens a file for reading only. The file pointer is placed at the beginning of
the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if Access mode
the file exists. If the file does not exist, creates a new file for reading and
writing.
a Opens a file for appending. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not exist,
it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end
of the file if the file exists. The file opens in the append mode. If the file
does not exist, it creates a new file for reading and writing.
The file object attributes.
• Once a file is opened and you have one file object, you can get
various information related to that file.
Closing file
• The close() method of a file object flushes any unwritten
information and closes the file object, after which no more
writing can be done.
• Syntax:
• fileObject.close()
Writing to File: