0% found this document useful (0 votes)
10 views69 pages

Module - Iv

The document provides an overview of Python dictionaries, detailing their structure as key-value pairs, properties, and various operations such as accessing, updating, adding, and deleting elements. It also covers methods for creating dictionaries, iterating through them, and the characteristics of keys and values. Additionally, the document briefly touches on regular expressions and their usage in Python.

Uploaded by

imrblack33
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views69 pages

Module - Iv

The document provides an overview of Python dictionaries, detailing their structure as key-value pairs, properties, and various operations such as accessing, updating, adding, and deleting elements. It also covers methods for creating dictionaries, iterating through them, and the characteristics of keys and values. Additionally, the document briefly touches on regular expressions and their usage in Python.

Uploaded by

imrblack33
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 69

DICTIONARIES

• The dictionary is the data type in Python


• Python Dictionary contains a collection of indices, which are
called keys
and a collection of values
• stores the data in a {key : value} pair format
• A dictionary is a collection which is unordered and does not
allow duplicates
• The values of a dictionary can be any data type.
• Keys are immutable data type (numbers, strings, tuple) and
values are mutable
• Elements in Dictionaries are accessed via keys and not by their
position
 Keys must be a single element
 Value can be any type such as list, tuple, integer, etc.
Operations on dictionary:
1. Accessing an element
2. Update
3. Add element
4. Membership
Membership
a={1: 'ONE', 2: 'two', 3: 'three'}
>>> 1 in a
True
>>> 3 not in a
False
Creating the dictionary
• The dictionary can be created by using multiple key-
value pairs enclosed with the curly brackets {}
Syntax:
Dict = {"Name": "Tom", "Age": 22}  {key : value}
Employee = {"Name": "John", "Age": 29,
"salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print(Employee)
Output :<class 'dict'>
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company':
'GOOGLE'}
• Python provides the built-in function dict() method
which is also used to create dictionary.
• The empty curly braces {} is used to create empty
dictionary.
Eg:
1. Print(dict())  o/p: { }

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])

a. values() >>> a. values() It displays list of values


in a dictionary
dict_values (['ONE', 'two', 'three'])

a.pop(key) >>> a.pop (3) Remove the element


with key and value from
>>> print(a) the dictionary.
{1: 'ONE', 2: 'two'}
>>> b={4:"four"}
>>> a.update(b) It will add the
a.update(dicti dictionary with the
onary) >>> print(a) existing dictionary
{1: 'ONE', 2: 'two', 3:
'three', 4: 'four'}

a={1: 'ONE', 2: 'two', 3:


len(a) 'three'} It returns the length
of the list
>>>len(a)  3
a={1: 'ONE', 2: 'two', 3:
'three'}
>>>a.clear() Remove all
clear() elements form the
>>>print(a) dictionary.
>>>{ }
a={1: 'ONE', 2: 'two', 3:
'three'} It will delete the
del(a) entire dictionary.
>>> del(a)
Iteration over sets
Add Members in sets
Remove elements from sets
pop()
Remove elements from sets
remove()
Remove elements from sets
discard()
Union of Two Sets

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

. Dot - It matches any characters except the newline character.

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)

* Asterisk - It matches zero or more occurrences of a pattern.

+ Plus - It is used when we want a pattern to match at least one.

? Question mark - It matches zero or one occurrence of a pattern.

Curly Braces - It matches the exactly specified number of occurrences


{} of a pattern

[] Bracket - It defines the set of characters


. (Dot): Matches any character except a
newline (\n).
import re
print(re.findall(r"a.b", "acb aab abb a b"))

# Output: ['acb', 'aab', 'abb']


^ (Caret): Matches the start of a string.

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"))

# Output: ['b', 'ba', 'baa', 'baaa']


+ (Plus): Matches one or more of the
preceding character.
import re

# Pattern to match 'a' followed by one or more


'b's
print(re.findall(r"ab+", "ab a bb abb abbb abc
a"))
# Output: ['ab', 'abb', 'abbb']
? (Question Mark): Matches zero or one of
the preceding character.
Ex1:
import re
# Pattern to match 'colou?r', where "u" is optional
print(re.findall(r"colou?r", "color colour colouur colr"))
# Output: ['color', 'colour']
Ex2:
import re
print(re.findall(r"ab?c", "ac abc abbc"))
# Output: ['ac', 'abc']
{} (Braces): Matches a specified number of
occurrences.
Ex1:
import re
print(re.findall(r"ab{2}c", "abc abbc abbbc"))
# Output: ['abbc']

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)

It is used to create a regular expression object


that can be used to match patterns in a string.
2. re.match(pattern, string, flags=0)
• It starts matching the pattern from the
beginning of the string.
• Returns a match object if any match is
found with information like start, end,
span, etc.
• Returns a NONE value in the case no
match is found.
import re
# The string we're searching in
text = "I have an apple and a banana."
# The regex pattern we're searching for
pattern = r"apple" # We want to find the word 'apple'
# Using re.search() to find the pattern in the string
match = re.search(pattern, text)
print(match)
# Check if a match was found
if match:
print("Match found:", match.group())
# match.group() retrieves the matched portion
else:
print("No match found.")

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.

• It can be used to perform substitutions in a


string based on a regular expression match.
Syntax:
• re.sub(pattern, replacement, string, count=0,
flags=0)
import re
text = "I like to eat apples.“
# Pattern to find the word 'apples'
pattern = r"apples“
# Replace 'apples' with 'oranges'
replacement = "oranges“
# Perform the substitution
new_text = re.sub(pattern, replacement, text)
print("Original text:", text)
print("New text:", new_text)
Output:
Original text: I like to eat apples.
New text: I like to eat oranges.
6.Split() function
import re
target_string = "My name is maximums and my
luck numbers are 12 45 78“
# split on white-space
word_list = re.split(r"\s+", target_string)
print(word_list
)
Output:
['My', 'name', 'is', 'maximums', 'and', 'my', 'luck',
'numbers', 'are', '12', '45', '78']

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy