dictionary_python_unit2
dictionary_python_unit2
CREATING A DICTIONARY
Dictionaries are created using curly braces {}.
The key is on the left side of the colon (:) and the value is on the right.
A comma separates each key-value pair.
Example :
Empty dictionary: my_dict = {}
Dictionary with integer keys: my_dict = {1: 'apple', 2: 'ball'}
Dictionary with mixed keys: my_dict = {'name': 'John', 1: [2, 4, 3]}
del keyword is used to delete the entire dictionary or the dictionary's items.
Syntax :del dict[key]
Considering the following code snippet for example:
port = {„80‟: "HTTP", „23‟ : "Telnet",„443‟ : "HTTPS"}
del port[23]
print(port)
Output: {80: 'HTTP', 443: 'HTTPS'}
get(key[, default]): Returns the value associated with the given key. If the key is not found, it
returns the optional default value (or None if not specified).
Example
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
age = my_dict.pop('age')
print(age) # Output: 25
print(my_dict)
Output: {'name': 'John', 'city': 'New York'}
country = my_dict.pop('country', 'Unknown')
print(country)
Output: Unknown
keys(): Returns a list (or an iterable) containing all the keys in the dictionary.
Python Programming Bhavani M
Example:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
keys = my_dict.keys()
print(keys)
Output: dict_keys(['name', 'age', 'city'])
pop(key[, default]): Removes and returns the value associated with the given key. If the key is not
found, it returns the optional default value (or raises a KeyError if not specified).
Example:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
age = my_dict.pop('age')
print(age)
Output: 25
print(my_dict)
Output: {'name': 'John', 'city': 'New York'}
setdefault(key[, default]): Returns the value associated with the given key. If the key is not found,
it adds the key with the optional default value (or None if not specified) to the dictionary.
Example:
values(): Returns a list (or an iterable) containing all the values in the dictionary.
Example
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
values = my_dict.values()
print(values)
Output: dict_values(['John', 25, 'New York'])
DICTIONARY METHODS
In Python, several built-in methods allow us to manipulate dictionaries.
These methods are useful for adding, removing and changing the values of dictionary.
Clear() Method
Removes all the elements from the dictionary
Syntax: dictionary.clear()
Here, clear() removes all the items present in the dictionary.
The clear() method doesn't take any parameters.
first_dict = {
"name": "ChampCode",
"founder": "Advaith",
"address": "Mysuru,Karnataka",
"Contact no":"8897868975",
"Email": "[email protected]",
Values() Method
The values method accesses all the values in a dictionary. Like the keys() method, it returns the
values in a tuple.
Syntax: dictionary.values()
first_dict = {
"name": "ChampCode",
"founder": "Advaith",
"address": "Mysuru,Karnataka",
"Contact no": "8897868975",
"Email": "[email protected]",
}
dict_values = first_dict.values()
print(dict_values)
Output: dict_values('ChampCode', 'Advaith', 'Mysuru,Karnataka', '8897868975',
'[email protected]')
Items() Method
The items() method returns all the entries of the dictionary in a list. In the list is a tuple
representing each of the items.
Syntax
dictionary.items()
Example:
first_dict = {
"name": "ChampCode",
"founder": "Advaith",
"address": "Mysuru,Karnataka",
Python Programming Bhavani M
"Contact no": ―8897868975‖,
"Email": "[email protected]",
}
items = first_dict.items()
print(items)
Output: dict_items[('name',"ChampCode"), ("founder","Advaith"), ( address":
"Mysuru,Karnataka"),("Contact no": "8897868975"), ( "Email": "[email protected]",
)]
keys() Method
The keys() returns all the keys in the dictionary. It returns the keys in a tuple – another Python data
structure.
first_dict = {
"name": "ChampCode",
"founder": "Advaith",
"address": "Mysuru,Karnataka",
"Contact no": ―8897868975‖,
"Email": "[email protected]",
}
items = first_dict.keys()
print(items)
Output: dict_keys('name', 'founder', 'address', 'Contact no', 'Email',)
Pop() Method
The pop() method removes a key-value pair from the dictionary. To make it work, you need to
specify the key inside its parentheses.
first_dict = {
"name": "ChampCode",
"founder": "Advaith",
"address": "Mysuru,Karnataka",
"Contact no": ―8897868975‖,
POPULATING A DICTIONARY
populating a dictionary refers to adding or assigning values to key-value pairs in the dictionary.
There are several ways to populate a dictionary in Python.
Here are a few examples:
print(my_dict)
Output: {'name': 'John', 'age': 25, 'city': 'New York'}
2. Dictionary literal:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
print(my_dict)
Output: {'name': 'John', 'age': 25, 'city': 'New York'}
These are some common methods to populate a dictionary in Python. Choose the method that
best suits your needs and the structure of the data you want to store in the dictionary.
Output:
name
age
city
Output:
John
25
New York
Output:
name John
age 25
city New York
Output:
Python Programming Bhavani M
name John
age 25
city New York
Output:
name John
age 25
city New York
TUPLE OPERATION
Tuples are immutable sequences in python and they support various operations. Here are
some common operations that can be performed on tuples:
1. Accessing Elements:
You can access individual elements of a tuple using indexing or slicing.
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0]) # Output: 1
print(my_tuple[1:4]) # Output: (2, 3, 4)
2. Concatenation:
You can concatenate two or more tuples using the + operator.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
3. Repetition:
You can repeat a tuple multiple times using the * operator.
my_tuple = (1, 2, 3)
repeated_tuple = my_tuple * 3
print(repeated_tuple)
Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
4. Length: You can determine the length of a tuple using the len() function.
my_tuple = (1, 2, 3, 4, 5)
print(len(my_tuple))
Output: 5
5. Membership Test: You can check if an element exists in a tuple using the in keyword.
my_tuple = (1, 2, 3, 4, 5)
print(3 in my_tuple) # Output: True
print(6 in my_tuple) # Output: False
6. Tuple Unpacking: You can assign the elements of a tuple to multiple variables simultaneously.
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c) # Output: 1 2 3
7. Iterating Over a Tuple: You can use a loop to iterate over the elements of a tuple.
my_tuple = (1, 2, 3, 4, 5)
for element in my_tuple:
1. len(tuple):
Returns the length (number of elements) of the tuple.
Example:
my_tuple = (1, 2, 3, 'a', 'b', 'c')
print(len(my_tuple))
Output: 6
2. tuple(iterable):
Converts an iterable object (such as a list, string, or another tuple) into a tuple.
Example:
my_list = [1, 2, 3, 4, 5]
converted_tuple = tuple(my_list)
print(converted_tuple)
Output: (1, 2, 3, 4, 5)
3. max(tuple):
Returns the largest element in the tuple.
Example:
my_tuple = (10, 5, 20, 15)
print(max(my_tuple))
Output: 20
4. min(tuple):
Returns the smallest element in the tuple.
Example:
Unordered: The elements in a set are not stored in any particular order, and their
positions can change.
Unique elements: A set cannot contain duplicate elements. If you try to add a duplicate
element to a set, it will only be stored once.
Mutable: You can add or remove elements from a set after it is created.
Membership test: Sets are useful for membership testing. You can quickly check if an
element is present in a set using the in operator.
Here's an example that demonstrates some basic operations with sets: my_set = {1, 2,
3, 4, 5}
print(len(my_set)) # Output: 5
my_set.add(6)
print(my_set) # Output: {1, 2, 3, 4, 5, 6}
my_set.remove(2)
print(my_set) # Output: {1, 3, 4, 5, 6}
OPERATIONS ON SETS
Sets in Python provide various operations to perform common set operations like union,
intersection, difference, and more. Here are some of the commonly used
1. Union: The union of two sets set1 and set2 contains all the unique elements from both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set)
Output: {1, 2, 3, 4, 5}
Alternatively, you can use the | operator to perform the union operation: union_set = set1 |
set2
2. Intersection: The intersection of two sets set1 and set2 contains the elements that are
common to both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set)
Output: {3}
Alternatively, you can use the & operator to perform the intersection operation: intersection_set
= set1 & set2
3. Difference: The difference between two sets set1 and set2 contains the elements that are in set1
but not in set2.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set)
Output: {1, 2}
Alternatively, you can use the - operator to perform the difference operation: difference_set =
Python Programming Bhavani M
set1 - set2
4. Symmetric Difference: The symmetric difference between two sets set1 and set2 contains
the elements that are in either set1 or set2, but not both.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1.symmetric_difference(set2) print(symmetric_difference_set)
Output: {1, 2, 4, 5}
Alternatively, you can use the ^ operator to perform the symmetric difference operation:
symmetric_difference_set = set1 ^ set2
These are just a few examples of the operations you can perform on sets in Python. Sets also
provide methods like isdisjoint(), issubset(), issuperset(), and more to perform additional set
operations and comparisons.
Sets in Python provide several built-in functions to perform operations and manipulations on
sets. Here are some of the commonly used built-in functions for sets:
1. len():
Returns the number of elements in a set.
Example
my_set = {1, 2, 3, 4, 5}
print(len(my_set)) # Output: 5
2. add():
Adds an element to a set.
Example
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)
Output: {1, 2, 4}
4. discard(): Removes an element from a set if it is present. Does not raise an error if the element
is not found.
Example
my_set = {1, 2, 3, 4}
my_set.discard(3)
print(my_set)
Output: {1, 2, 4}
5. pop(): Removes and returns an arbitrary element from a set. Raises a KeyError if the set is
empty.
Example
my_set = {1, 2, 3, 4} removed_element
= my_set.pop() print(removed_element)
Output: The removed element (e.g., 1)
print(my_set)
Output: The modified set without the removed element
6. clear():
Removes all elements from a set, making it empty.
Example
my_set = {1, 2, 3, 4}
my_set.clear()
Python Programming Bhavani M
print(my_set)
Output: set()
7. copy(): Creates a shallow copy of a set.
Example
my_set = {1, 2, 3}
copy_set = my_set.copy()
print(copy_set)
Output: {1, 2, 3}
8. issubset():
Checks if a set is a subset of another set.
Example
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
print(set1.issubset(set2))
Output: True
9. issuperset():
Checks if a set is a superset of another set.
Example
set1 = {1, 2, 3, 4, 5}
set2 = {1, 2, 3}
print(set1.issuperset(set2))
Output: True
10. isdisjoint():
Checks if two sets have no common elements.
Example
set1 = {1, 2, 3}
SET METHODS
Sets in Python have several built-in methods that provide various operations and manipulations.
Here are some commonly used set methods:
1. add():
Adds an element to the set.
Example
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)
Output: {1, 2, 3, 4}
2. remove():
Removes an element from the set. Raises a KeyError if the element is not found.
Example
my_set = {1, 2, 3, 4}
my_set.remove(3)
print(my_set)
Output: {1, 2, 4}
3. discard():
Removes an element from the set if it is present. Does not raise an error if the element is not
found.
Exampe
my_set = {1, 2, 3, 4}
Python Programming Bhavani M
my_set.discard(3)
print(my_set)
Output: {1, 2, 4}
4. pop():
Removes and returns an arbitrary element from the set. Raises a KeyError if the set is
empty.
Example
my_set = {1, 2, 3, 4}
removed_element = my_set.pop()
print(removed_element)
Output: The removed element (e.g., 1)
print(my_set)
Output: The modified set without the removed element
5. clear(): Removes all elements from the set, making it empty.
Example
my_set = {1, 2, 3, 4}
my_set.clear()
print(my_set)
Output: set()
6. copy():
Creates a shallow copy of the set.
Example
my_set = {1, 2, 3}
copy_set = my_set.copy()
print(copy_set)
Output: {1, 2, 3}
Python Programming Bhavani M
7. union():
Returns a new set that is the union of the set and one or more other sets.
Example
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set)
Output: {1, 2, 3, 4, 5}
8. intersection(): Returns a new set that is the intersection of the set and one or more other sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set)
Output: {3}
9. difference(): Returns a new set that contains the elements in the set but not in one or more other
sets.
Example
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set)
Output: {1, 2}
A file is a named location on the system storage which stores related data for
future purposes.
The data can be anything like a simple text file, video or audio file, or any
complex executable programs.
Files consist of three important parts as listed below.
The header holds the metadata of the file i.e., the details like name, size,
type, etc
Data is the contents in the file like texts, pictures, audio, etc.
EOF indicates the end of the file.
when it comes to accessing a file we must know where we have stored the file.
For that, we use the File path which gives the route or location of the file. The
file path contains 3 parts as listed below.
The folder path indicates the location of the folder in which the file
resides.
Filename indicates the actual name of the file.
File extension shows the type of file.
Types of Files in python
Types of files
Binary Files are files that contain non-text values like images, audios etc.
Usually, binary files contain the objects in the form of zeros and ones.
When you want to work with files, you need to perform the 3 basic operations
which are listed below in the order of processing.
Open a file
Read or write operation
Close a file
The above flow chart gives you the workflow of file handling in python.
Initially, we need to create a file. This can be done manually by the user
wherever he needs and save it with a valid filename and extension. Also,
python supports file creation which you will encounter in future sessions.
Modes of files.
R(Read Default mode):- Open file for reading.It shows an error if the
file does not exist
You can use several attributes to get the details of the file once after a file object
gets created. Some of the attributes are listed below.
.mode: returns the mode of the file with which file is opened.
Most importantly there are 4 types of operations that can be handled byPython on files:
Open
Read
Write
Close
Rename
Delete
Here file_name is the name of the file that youwant to open and file_name should have the file
extension. Which means in test.txt – the term test is the name of the file and .txt is the
extension of the file.
The mode in the open function syntax will tell Python as what operation you want to do on a
file.
‘r’ – Read Mode: Read mode is used only to read data from the file.
‘w’ – Write Mode: This mode is used when you want to write data into the file or modify
it. Remember write mode overwrites the data present inthe file.
‘a’ – Append Mode: Append mode is used to append data to the file.Remember data
will be appended at the end of the file pointer.
Example 1:
In the above example, we are opening the file named “test.txt” present at the location
“C:/Documents/Python/” and we are opening the same file ina read-write mode which gives us
more flexibility.
In order to read a file in python, we must open the file in read mode.
There are three ways in which we can read the files in python.
read([n])
readline([n])
Example 1:
print(my_file.read(5))
Output:
Hello
Here we are opening the file test.txt in a read-only mode and are reading onlythe first 5
characters of the file using the my_file.read(5) method.
In order to write data into a file, we must open the file in write mode.
We need to be very careful while writing data into the file as it overwrites the content
present inside the file that you are writing, and all the previous data will be erased.
We have two methods for writing data into a file as shown below.
write(string)
writelines(list)
Example 1:
my_file.write(“Hello World”)
The above code writes the String “Hello World” into the “test.txt” file.
Output:
Python Programming Bhavani M
Example 2:
fruits = [“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”]
my_file.writelines(fruits)
The above code writes a list of data into the „test.txt‟ file simultaneously.
Output:
To append data into a file we must open the file in “a+” mode so that wewill have access to
both the append as well as write modes.
Example 1:
my_file.write (“Strawberry”)
Output:
Example 2:
my_file.write (“\nGuava”)
The above code appends the string “Guava” at the end of the “test.txt” file in anew line.
Output:
Example 1:
print(my_file.read())
my_file.close()
This rename() method accepts two arguments i.e. the current file name and thenew file name.
Syntax:
os.rename(current_file_name, new_file_name)
Example 1:
import os
os.rename(“test.txt”, “test1.txt”)
Here “test.txt” is the current file name and “test1.txt” is the new file name.
remove() method:
We use the remove() method to delete the file by supplying the file name or thefile location that you
want to delete.
Syntax:
os.remove(file_name)
Example 1:
import os
Attribute Description
Example:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.close()
Output:
What is the file name? C:/Documents/Python/test.txt
In file handling, the file path and name refer to the location and name of a file that you want to
read from or write to.
The file path specifies the directory or folder structure where the file is located, and the file
name is the actual name of the file itself.
The file path can be either an absolute path or a relative path. An absolute path provides the full
directory structure starting from the root directory, while a relative path is defined relative to
the current working directory ofthe program.
Here are a few examples to illustrate the file path and name in file handlingusing Python:
file.write("Hello, world!")
file.write("Hello, world!")
In this case, the file output.txt will be created in the current working directory.
It's important to note that the actual file name should be included in the file path. The file name
should have the appropriate file extension to indicate thefile type (e.g., .txt, .csv, .json, etc.).
Additionally, ensure that you have the necessary permissions to read from or write to the
specified file path.
FORMAT OPERATOR
In file handling the format operator is typically used to specify the formatting of data
when reading from or writing to a file.
In Python, the format operator is represented by the % symbol. It allowsyou to format strings
by replacing placeholders with corresponding values.
The format operator is often used in conjunction with the % formatting codes, which specify
the type and format of the values being inserted.
Here's a basic example that demonstrates the usage of the format operator in file handling with
Python:
data = file.read()
Python Programming Bhavani M
print(data)
Name: JohnAge: 25