Module - Iv
Module - Iv
2. D = {}
D= dict({1: 'Java', 2: 'T', 3:'Point'}) o/p:
print(D) {1:
'Java', 2: 'T', 3: 'Point'}
Accessing the dictionary values
• We have discussed how the data can be accessed in the list and
tuple by using the indexing.
• However, the values can be accessed in the dictionary by using the
keys as keys are unique in the dictionary.
Eg:
E= {"Name": "John", "Age": 29,
"salary":25000,"Company":"GOOGLE"}
Print(E["Name"]) o/p: john
Print(E["salary"]) 25000
Updating:
E[“Name”]=“nithin”
E[“salary”]=50000
o/p:
{'Name': 'nithin', 'Age': 29, 'salary': 50000, 'Company': 'GOOGLE'}
Adding dictionary values
• The dictionary is a mutable data type, and its values can be
updated by using the specific keys.
• The value can be updated along with key Dict[key] = value.
• Note: If the key-value already present in the dictionary, the value
gets updated. Otherwise, the new keys added in the dictionary.
Let's see an example to update the dictionary values.
Eg:
D={}
D[0]="name“ o/p:
D[1]=45 {0: 'name', 1: 45, 2: 'python'}
D[2]="python“ {0: 'name', 1: 45, 2:
'program'}
print(D)
D[2]="program“
print(D)
Deleting elements using del keyword:
• The items of the dictionary can be deleted by
using the del keyword as given below.
Eg:
E= {"Name": "John", "Age": 29,
"salary":25000,"Company":"GOOGLE"}
del E["Name"]
del E["Company"]
print(E)
o/p:
{'Age': 29, 'salary': 25000}
Using pop() method
• The pop() method accepts the key as an
argument and remove the associated value.
Eg:
Dict = {1: 'JavaTpoint', 2: 'Peter', 3: 'Thomas'}
Dict.pop(3)
print(Dict)
o/p:
{1: 'JavaTpoint', 2: 'Peter'}
Iterating Dictionary (Looping):
A dictionary can be iterated using for loop as given below.
Example 1
# for loop to print all the keys of a dictionary
E= {"Name": "John", "Age": 29,
"salary":25000,"Company":"GOOGLE"}
for x in E:
print(x)
Output:
Name
Age
Salary
Company
Example 2
#for loop to print all the values of the dictionary
E = {"Name": "John", "Age": 29,
"salary":25000,"Company":"GOOGLE"}
for x in E:
print(E[x])
o/p:
John
29
25000
GOOGLE
Example - 3
#for loop to print the values of the dictionary by
using values() method.
E= {"Name": "John", "Age": 29,
"salary":25000,"Company":"GOOGLE"}
for x in E.values():
print(x)
Output:
John
29
25000
GOOGLE
Example 4
#for loop to print the items of the dictionary by
using items() method
E = {"Name": "John", "Age": 29,
"salary":25000,"Company":"GOOGLE"}
for x in E.items():
print(x)
o/p:
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')
Properties of Dictionary keys
1. In the dictionary, we cannot store multiple
values for the same keys. If we pass more than
one value for a single key, then the value which
is last assigned is considered as the value of the
key.
Eg:
E={"Name":"John","Age":29,"Salary":25000,"Compa
ny":"GOOGLE","Name":“abi"}
print(Employee)
o/p:
{'Name': ‘abi', 'Age': 29, 'Salary': 25000,
'Company': 'GOOGLE'}
2. In python, the key cannot be any mutable object.
We can use numbers, strings, or tuples as the key, but
we cannot use any mutable object like the list as the
key in the dictionary.
Eg:
E = {"Name": "John", "Age": 29,
"salary":25000,"Company":"GOOGLE",
[100,201,301]:"Department ID"}
o/p:
It shows error
Methods in dictionary:
Method Example Description
a. copy( ) a={1: 'ONE', 2: 'two', 3: 'three'} It returns copy of the
>>> b= a.copy() dictionary.
>>> print(b) {1: 'ONE', 2: 'two', 3:
'three'}
a. items() >>> a. items() It displays a list of
dictionary’s (key, value)
dict_items([(1, 'ONE'), (2, 'two'), (3, pairs.
'three')])
a. keys() >>> a. keys() It displays list of keys in
a dictionary
dict_keys([1, 2, 3])
s1={1,2,3} Output
s2={3,4,5} {1, 2, 3, 4, 5}
print(s1.union(s2))
INTERSECTION OF TWO SETS
s1={1,2,3,4,6,5} Output:
s2={3,4,5,8,9,11,2} {2, 3, 4, 5}
print(s1.intersection(s2))
SET DIFFERENCE
s1={1,2,3,4,6,5}
s2={3,4,5,8,9,11,2} Output:
print(s1.difference(s2)) {1, 6}
SYMMETRIC DIFFERENCE
s1={1,2,3,4,6,5}
Output:
s2={3,4,5,8,9,11,2}
{1, 6, 8, 9, 11}
print(s1.symmetric_difference(s2))
issubset() Method
Return True if all items in set x are
present in set y:
Syntax
• set.issubset(set1)
Shorter Syntax
• set <= set1
EXAMPLES
x = {"a", "b", "c"} x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"} y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y) z = x <= y
print(z) print(z)
OUTPUT: OUTPUT:
True True
issuperset() method
• The issuperset() method returns True if all
items in the specified set exists in the original
set, otherwise it returns False.
Syntax
• set.issuperset(set)
Shorter Syntax
• set >= set1
Examples
x = {"f", "e", "d", "c", "b", "a"} x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"} y = {"a", "b", "c"}
z = x.issuperset(y) z = x >= y
print(z) print(z)
OUTPUT: OUTPUT:
True True
Regular Expression in Python
• Regular Expression, is a sequence of
characters that forms a search pattern.
• RegEx can be used to check if a string
contains the specified search pattern.
• Python has a built-in package called re, which
can be used to work with Regular Expressions.
Syntax
import re
Meta characters or Special Characters
Character Meaning
s
Caret - It is used to match the pattern from the start of the string. (Starts
^ With)
Dollar - It matches the end of the string before the new line character.
$ (Ends with)
import re
print(re.findall(r"^hello", "hello world hello"))
# Output: ['hello']
$ (Dollar): Matches the end of a string.
import re
print(re.findall(r"world$", "hello world"))
# Output: ['world']
* (Asterisk): Matches zero or more of the
preceding character.
import re
print(re.findall (r"ba*", "b ba baa baaa"))
Ex2:
import re
# Pattern to match 'a' followed by exactly three 'b's
print(re.findall(r"ab{3}", "ab abbb abbbb abbbbb"))
# Output: ['abbb']
[] (Square Brackets): Matches any one
character within the brackets.
Ex1:
import re
print(re.findall(r"a[bc]d", "abd acd add"))
# Output: ['abd', 'acd']
Ex2:
import re
# Pattern to match 'a' followed by either 'x' or 'y', then
'z'
print(re.findall(r"a[xy]z", "axz ayz abz axyz ax az"))
# Output: ['axz', 'ayz']
Special Sequences:
Charact Meaning
ers
\d It matches any digit and is equivalent to [0-9].
It matches any non-digit character and is equivalent to
\D [^0-9].
It matches any white space character and is equivalent to
\s [\t\n\r\f\v]
It matches any character except the white space character
\S and is equivalent to [^\t\n\r\f\v]
It matches any alphanumeric character and is equivalent
\w to [a-zA-Z0-9]
It matches any characters except the alphanumeric
\W character and is equivalent to [^a-zA-Z0-9]
Special Sequences:
Charact Meaning
ers
It matches the defined pattern at the start of the
\A
string.
r"\bxt" - It matches the pattern at the beginning of
a word in a string.
\b
r"xt\b" - It matches the pattern at the end of a
word in a string.
\B This is the opposite of \b.
It returns a match object when the pattern is at the
\Z
end of the string.
\d - Matches any digit (0–9)
import re
text = "My phone number is 123-456-7890."
pattern = r"\d“
# Matches any digit
matches = re.findall(pattern, text)
print(matches)
Output:
['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
\D - Matches any character that is NOT a
digit
import re
text = "My phone number is 123-456-7890."
pattern = r"\D"
# Matches any non-digit character
matches = re.findall(pattern, text)
print(matches)
Output:
['M', 'y', ' ', 'p', 'h', 'o', 'n', 'e', ' ', 'n', 'u', 'm', 'b', 'e', 'r',
' ', 'i', 's', ' ', '-', '-', '.']
\s - Matches any whitespace character
(space, tab, newline, etc.)
import re
text = "Hello, world! This is a test."
pattern = r"\s"
# Matches any whitespace character
matches = re.findall(pattern, text)
print(matches)
Output:
[' ', ' ', ' ', ' ', ' ']
\S - Matches any non-whitespace character
import re
text = "Hello, world! This is a test."
pattern = r"\S"
# Matches any non-whitespace character
matches = re.findall(pattern, text)
print(matches)
Output:
['H', 'e', 'l', 'l', 'o', ',', 'w', 'o', 'r', 'l', 'd', '!', 'T', 'h', 'i',
's', 'i', 's', 'a', 't', 'e', 's', 't', '.']
\W - Matches any character that is NOT a
word character (non-alphanumeric)
import re
text = "Hello, world! This is a test."
pattern = r"\W"
# Matches any non-word character
matches = re.findall(pattern, text)
print(matches)
Output:
[',', ' ', '!', ' ', ' ', ' ', ' ']
\w - Matches any word character
(alphanumeric + underscore)
import re
text = "Hello, world! This is a test."
pattern = r"\w"
# Matches any word character
matches = re.findall(pattern, text)
print(matches)
Output:
['H', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', 'T', 'h', 'i', 's', 'i', 's',
'a', 't', 'e', 's', 't']
RegEx Functions
• compile - It is used to turn a regular pattern into an object of a
regular expression that may be used in a number of ways for
matching patterns in a string.
• search - It is used to find the first occurrence of a regex
pattern in a given string.
• match - It starts matching the pattern at the beginning of the
string.
• fullmatch - It is used to match the whole string with a regex
pattern.
• split - It is used to split the pattern based on the regex pattern.
• findall - It is used to find all non-overlapping patterns in a
string. It returns a list of matched patterns .
RegEx Functions
• finditer - It returns an iterator that yields match
objects.
• sub - It returns a string after substituting the first
occurrence of the pattern by the replacement.
• subn - It works the same as 'sub'. It returns a
tuple (new_string, num_of_substitution).
• escape - It is used to escape special characters in
a pattern.
• purge - It is used to clear the regex expression
cache.
1. re.compile(pattern, flags=0)
Output:
<re.Match object; span=(10, 15), match='apple'>
Findall function
To find all occurrences of a pattern in a string
and returns them as a list. If no matches are
found, it returns an empty list.
Syntax:
re.findall(pattern, string, flags=0)
import re
text = "My phone number is 123-456-7890 and my
friend's number is 987-654-3210."
# Pattern to find all digits
pattern = r"\d+"
# Match one or more digits
# Using re.findall() to find all occurrences of digits
matches = re.findall(pattern, text)
print("Digits found:", matches)
Output:
Digits found: ['123', '456', '7890', '987', '654', '3210']
4.finditer() function
• It is similar to re.findall(), but instead of
returning a list of strings, it returns an iterator
of match objects for all non-overlapping
matches of a pattern in a string.
• This allows you to access additional
information about each match, such as the
starting and ending positions of the match, or
the captured groups in the pattern.
import re
Output:
text = "I love Python programming.
Match found:
Python is great.“
Python
# Pattern to find the word 'Python'
Start position: 7
pattern = r"Python“
End position: 13
# Using re.finditer() to find all
occurrences of 'Python'
------------------------
matches = re.finditer(pattern, text)
----------------
# Loop through the match objects and
print match details Match found:
Python
for match in matches:
Start position: 27
print(f"Match found: {match.group()}")
print(f"Start position: {match.start()}") End position: 33
print(f"End position: {match.end()}") ---------------------------
-------------
print("-" * 40)
5.sub() function
• The re.sub() function in Python is used to
replace occurrences of a pattern in a string
with a specified replacement string.