0% found this document useful (0 votes)
4 views89 pages

Python Data Types - 4-2

The document provides an overview of Python data types, focusing on strings and lists. It explains string characteristics, methods, and immutability, as well as list properties, functions, and methods for adding, accessing, and removing elements. Additionally, it includes examples and assignments to practice string and list manipulation.

Uploaded by

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

Python Data Types - 4-2

The document provides an overview of Python data types, focusing on strings and lists. It explains string characteristics, methods, and immutability, as well as list properties, functions, and methods for adding, accessing, and removing elements. Additionally, it includes examples and assignments to practice string and list manipulation.

Uploaded by

dextrojha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Data Types

Python has the following data types built-in by default, in


these categories:
1) Numeric Types: int, float, complex
2) Text Type: str
3) Sequence Types: list, tuple
4) Mapping Type: dict
5) Set Types: set
String Datatype
Strings are sequences of character data. The
string type in Python is called str.

String literals may be delimited using either


single or double quotes.
Single line and multiline string
S1 = 'Welcome to CME'
print(S1)
S1 = “HELLO ALL"
print(S1)
print(type(S1))
# Creating String with triple Quotes allows multiple lines
S1 = ‘’’ This is multiline string.
It can be used for paragraph data.
It always have three single or double quotes’’’
print("Creating a multiline String: ")
print(S1)
Output:
Welcome to CME
HELLO ALL
<class 'str'>
Creating a multiline String:
This is multiline string.
It can be used for paragraph data.
It always have three single or double quotes
Accessing elements of a string

W E L C O M E T O C M E

0 1 2 3 4 5 6 7 8 9 10 11 12 13

-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1


S1 = "College of Military Engineering"
print("Initial String: ")
print(S1)
print("First character of String is: ")
print(S1[0])
print("Last character of String is: ")
print(S1[-1])

Output:
Initial String:
College of Military Engineering
First character of String is:
C
Last character of String is:
g
Deleting/Updating from a String
⚫ In Python, Updation or deletion of characters from a String is
not allowed.
⚫ This will cause an error.
⚫ Strings are immutable, hence elements of a String cannot be
changed once it has been assigned.
⚫ Only new strings can be reassigned to the same name.
String Methods/Functions
Method name Purpose
[Link]() converts the first character to upper case
[Link](str) returns the number of times a specified value occurs in a string
[Link](str) returns true if the string ends with the specified value
[Link](str) searches the string for a specified value and returns the position
of where it was found
[Link]() returns true if all characters in the string are alphanumeric
[Link]() returns true if all characters in the string are in the alphabet
[Link]() returns true if all characters in the string are digits
[Link]() returns true if all characters in the string are upper case
[Link](str) returns true if the string starts with the specified value
method name purpose
sorted(str) returns a list of sorted characters of a string
reversed(str) returns a list of reversed characters of a string
[Link]() replaces all occurrences of the search string with the replacement string
[Link]() converts a string to uppercase
[Link]() converts a string to lowercase
[Link]() used to split a string into the list of strings based on a delimiter.
join(str) returns a new string that is the concatenation of the strings with string
object as a delimiter.
len(str) returns the length of a string

ord(str) returns ascii value of a string

chr(ascii value) returns a string of the given ascii value


s1=“college of Military Engineering" Output
print([Link]()) College of military engineering

print([Link]("i")) 4

print([Link]("ing")) True

print([Link]("Col")) True

print([Link](“m")) 11

print([Link]()) False
print([Link]()) False
s2="Hello"
print([Link]()) True
print([Link]()) False
print([Link]()) False
s1="College of Military Engineering" Output
print(sorted(s1)) [' ', ' ', ' ', 'C', 'E', 'M', 'a', 'e', 'e',
'e', 'e', 'f', 'g', 'g', 'g', 'i', 'i', 'i', 'i',
'l', 'l', 'l', 'n', 'n', 'n', 'o', 'o', 'r', 'r',
't', 'y’]

['g', 'n', 'i', 'r', 'e', 'e', 'n', 'i', 'g', 'n',
print(list(reversed(s1))) 'E', ' ', 'y', 'r', 'a', 't', 'i', 'l', 'i', 'M', '
', 'f', 'o', ' ', 'e', 'g', 'e', 'l', 'l', 'o',
'C']
Replace
• The replace() function is g = 'Hello Bob'
n = [Link]('Bob','Jane')
like a “search and replace” print (n)
operation in a word
processor Output
Hello Jane

• It replaces all occurrences n = [Link]('o','X')


of the search string with print (n)
the replacement string Output
HellX BXb
• replace() actually returns a *copy* of the
argument string with relevant parts replaced.
• The original string is left intact.
• Strings are immutable in Python.
Making everything UPPER CASE/lower case
g = 'Hello Bob'
n= [Link]()
You can make a copy of a string in print (n)
lower case or upper case
Output
Often when we are searching for a HELLO BOB
string using find() - we first convert
w = [Link]()
the string to lower case so we can print (w)
search a string regardless of case
Output
hello bob
Get a single string from two given strings and swap the first two characters
of each string. (String Slicing)
a='abcdef' Output
b='xyzlmn'
print(a[ :2]) ab
print(b[2: ]) zlmn
print(b[ :2] + a[2: ]) Xycdef
print(a[1:5:2]) # acts as range function bd
print(a[ : : -1]) # reverse the string
fedcba
Ord() and chr() functions
ord()-it returns ascii value of a string
print(ord(‘A’))
65

chr()-it returns a string of the given integer


print(chr(65))
A
Splitting a string Joining a string

a = "this is a string"
a = [Link](" ") a = "-".join(a)
# a is converted to a list of strings. print (a)
print (a)
Output
Output

['this', 'is', 'a', 'string’] this-is-a-string


Calculate length of a string

a=“this is a string”
b=len(a)
print(b)

output
16
Assignments
1) Program to check whether a string is palindrome or not
Input:- NAYAN Output:-It is palindrome
2) Write a Python program to add 'ing' at the end of a given string
(length should be at least 3)
3)If the given string already ends with 'ing' then add 'ly' instead. If the
string length of the given string is less than 3, leave it unchanged.
4) Write a Python program to change a given string to a new string
where the first and last chars have been exchanged.
5) Write a Python program to delete all occurrences of a specified
character in a given string.
6) Program to count the number of vowels and consonants in a string
Assignments
7) Python program to check if given string is pangram
A pangram is a sentence containing every letter in the English Alphabet.
Input : The quick brown fox jumps over the lazy dog
Output : Yes Input : abcdefgxyz Output : No

8) Python program to perform encryption & decryption on the given string using
ceaser cipher. Input the key value and string. Input :- Hello key=3 Output:- khoor

9) Given a string, return the sum and average of the digits that appear in the string,
ignoring all other characters
Input: str1 = "English = 78 Science = 83 Math = 68 History = 65"
Output: sum is 294 average is 73.5
Lists
⚫ Lists are like the arrays, collection of elements.
⚫ Lists need not be homogeneous always.
⚫ A single list may contain Integers, Strings, as well as Objects.
⚫ Lists are mutable, and hence, they can be altered even after their
creation.
⚫ Lists are ordered and have a definite count.
⚫ The elements in a list are indexed according to a definite sequence and
the indexing of a list is done with 0 being the first index.
⚫ Each element in the list has its definite place in the list, which allows
duplicating of elements in the list
List Functions
▪ append () – Adds an element to the end of the list
▪ clear () – Removes all elements from the list
▪ count () – Returns the total number of items passed as an argument
▪ extend () – Adds a list of elements to some other list
▪ index () – Returns the index of an element (Note: If the same element
appears multiple times in the list then the index of the first match is returned)
▪ insert () – Inserts an element to the list at the defined index
▪ pop () – Eliminates and returns an element from the list
▪ remove () – Eliminates an element from the list
▪ reverse () – Reverses the order of all elements of the list
▪ sorted () – Sort all elements of a list in the ascending or descending order
• Len()- To give total count of elements
• List()-to create a list
• Sum()- to calculate sum of all elements
• Max()- to find maximum value element
• Min()-to find minimum value element
Adding Elements to a List
⚫ Only one element at a time can be added to the list by
using append() method.
⚫ For addition of element at the desired position,

insert() method is used.


⚫ extend(), this method is used to add multiple

elements at the same time at the end of the list.


# Creating a List
List = [ ]
print("Initial blank List: ")
print(List)
# Addition of Elements in the List
[Link](1)
[Link](2)
[Link](4)
print("List after Addition of Three elements: ")
print(List)
# Addition of Element at specific Position (using Insert
Method)
[Link](3, 12)
[Link](0, ‘CME')
print("List after performing Insert Operation: ")
print(List)
# Addition of multiple elements to the List at the end (using
Extend Method)
[Link]([8, ‘EODE', 'Always'])
print("List after performing Extend Operation: ")
print(List)
Output:
Initial blank List:
[]
List after Addition of Three elements:
[1, 2, 4]
List after performing Insert Operation:
[‘CME', 1, 2, 4, 12]
List after performing Extend Operation:
['Geeks', 1, 2, 4, 12, 8, ‘EODE', 'Always']
Accessing elements from the List
⚫ To access the list items refer to the index number.
⚫ Use the index operator [ ] to access an item in a list. The

index must be an integer.


⚫ Nested list is accessed using nested indexing.

⚫ Negative indexing means beginning from the end, -1

refers to the last item, -2 refers to the second last item


etc. e.g. List[-3]
List = [“Hello", "For", “All"]
print("Accessing element from the list")
print(List[0])
print(List[2])
print("Accessing element using negative indexing")
# print the last element of list
print(List[-1])
# print the third last element of list
print(List[-3])
Output:
Accessing element from the list
Hello
All
Accessing element using negative indexing
All
Hello
Removing Elements from the List
⚫ Elements can be removed from the List by using built-in
remove() function but an Error arises if element doesn’t exist
in the list.
⚫ Pop() function can also be used to remove and return an
element from the list, but by default it removes only the last
element of the list, to remove an element from a specific
position of the List, index of the element is passed as an
argument to the pop() method.
⚫ Note – Remove method in List will only remove the first
occurrence of the searched element.
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)
# Removing elements from List using Remove()
method
[Link](5)
[Link](6)
print("List after Removal of two elements: ")
print(List)
[Link]()
print("List after popping an element: ")
print(List)
# Removing element at a specific location from the
list using the pop() method
[Link](2)
print("List after popping a specific element: ")
print(List)
# Empty the list
[Link]()
Print(“List after clearing”)
Print(List)
Output:
# Creating a List
Initial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
List after Removal of two elements:
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
List after popping an element:
[1, 2, 3, 4, 7, 8, 9, 10, 11]
List after popping a specific element:
[1, 2, 4, 7, 8, 9, 10, 11]
List after clearing
[]
l1=[10,20,30,40.5] Output
100.5
print(sum(l1))
40.5
print(max(l1)) 10
print(min(l1)) Traceback (most recent call last):
l2=["hello",10,20] File
"C:/Users/[Link]/Desktop/SP/
print(sum(l2)) list [Link]", line 6, in <module>
print(sum(l2))
print(max(l2))
TypeError: unsupported operand type(s)
for +: 'int' and 'str'
l1=[10,20,30,40.5] Output
[Link]()
print(l1) [40.5, 30, 20, 10]
print([Link](10)) 1
print(sorted(l1)) [10, 20, 30, 40.5]
Nested list (Matrix representation)
#Access matrix elements and print
a=[[1,2,3],[4,5,6]]
for i in range(len(a)):
for j in range(len(a[0])):
print(a[i][j],end=“ “)

Output
123
456
Input a matrix
a=[]
for i in range(3):
b=[]
for j in range(3):
c=int(input(“enter matrix element”))
[Link](c)
[Link](b)
Addition of two matrices
a=[[1,2,3],[4,5,6]]
b=[[7,8,9],[0,1,2]]
c=[[0,0,0],[0,0,0]]
if len(a)==len(b) and len(a[0])==len(b[0]): #to check square matrix
for i in range(len(a)):
for j in range(len(a[0])):
c[i][j]=a[i][j]+b[i][j]
print(c[i][j],end=" ")
print()
Output
8 10 12
468
List Comprehension
Easy way of creating a list.
a=[1,2,3,25,30,35,42,49,8,7]
b=[num for num in a if num>20 and num<50]
print(b)

Output
[25,30,35,42,49]
a=[(x , x**2, x**3) for x in range(1,10)]
print(a)

Output
[(1,1,1),(2,4,8),(3,9,27),(4,16,64)]
Assignment
1. Write a Python program to count the number of strings where the string length is 2 or
more and the first and last character are same from a given list of strings.
Sample List : ['abc', 'xyz', 'aba', '1221']
Expected Result : 2
2. Write a Python function that takes two lists and returns True if they have at least one
common member.
3. Write a Python program to print a specified list after removing the 0th, 4th and 5th
elements.
Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
Expected Output : ['Green', 'White', 'Black’]
4. Write a Python program to find all the values in a list are greater than a specified
number.
5. Create a list of integers which specify the length of each word in a certain sentence, but
only if the word is not the word "the“ using list comprehension. Input:- "the quick
brown fox jumps over the lazy dog“
6. Create a new list called "newlist" out of the list "numbers", which contains only the
positive numbers from the list, as integers.
Input:- numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
Tuple
⚫ Tuple is an ordered collection of elements.
⚫ The sequence of values can be of any type, and they are indexed by
integers.
⚫ Tuples are immutable.
⚫ Tuples are created by placing sequence of values separated by
‘comma’ with parentheses ().
⚫ Tuples can contain any number of elements and of any datatype
(like strings, integers, list, etc.).
⚫ Having one element in the parentheses, there must be a trailing
‘comma’ to make it a tuple.
Tuple Methods
count()-returns occurrences of elements in a tuple
Index()-returns first position value of an element
Len () – Gives out the total length of some tuple
max () – Returns the biggest value from a tuple
min () – Returns the smallest value from a tuple
tuple () – Converts some list into a tuple
Zip()- returns an iterator of tuples(both in list & tuple)
Sum()- returns sum of elements (both in list & tuple)
Reversed()- returns the elements in reverse order(in list , string and
tuple)
sorted()-sorts the tuple contents
# Creating an empty tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)
# Creating a Tuple with the use of Strings
Tuple1 = ('', 'For')
print("Tuple with the use of String: ")
print(Tuple1)
# Creating a Tuple with the use of list
list1 = [1, 2, 4, 5, 6]
print("Tuple using List: ")
print(tuple(list1))
# Creating a Tuple with the use of built-in function
Tuple1 = tuple('Geeks')
print("Tuple with the use of function: ")
print(Tuple1)
# Creating a Tuple with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("Tuple with nested tuples: ")
print(Tuple3)
Output:
Initial empty Tuple:
()
Tuple with the use of String:
('Geeks', 'For')
Tuple using List:
(1, 2, 4, 5, 6)
Tuple with the use of function:
('G', 'e', 'e', 'k', 's')
Tuple with nested tuples:
((0, 1, 2, 3), ('python', 'geek'))
Accessing element of a tuple

Use the index operator [ ] to access an item in a tuple. The


index must be an integer. Nested tuples are accessed using
nested indexing.
tuple1 = tuple(1, 2, 3, 4, 5)
# Accessing element using indexing
print("First element of tuple")
print(tuple1[0])
# Accessing element from last negative indexing
print("Last element of tuple")
print(tuple1[-1])
print("Third last element of tuple")
print(tuple1[-3])
Output:
Frist element of tuple
1
Last element of tuple
5
Third last element of tuple
3
Zip and unzip elements
coordinate=('x','y','z')
value=(3,4,5)
result=zip(coordinate,value)
result_list=list(result)
print(result_list)
# To unzip the list
c,v=zip(*result_list)
print("c =", c)
print("v =", v)
Output
[('x',3),('y',4),('z',5)
C=('x','y','z')
V=(3,4,5)
Sum, max, min functions
numbers=(1,2,3,4,5)
nsum=sum(numbers)
print(nsum)
print(max(numbers))
print(min(numbers))

output
15
5
1
a=(2,5,1,3,6)
print(sorted(a))
b=tuple(reversed(a))
print(b)

Output
(1, 2, 3, 5, 6)
(6, 3, 1, 5, 2)
Exercises
• Write a Python program to find the repeated items of a tuple.
• Write a Python program to remove an item from a tuple.
• Write a Python program to calculate the average value of the numbers in a
given tuple of tuples.
Original Tuple:
((10, 10, 10, 12), (30, 45, 56, 45), (81, 80, 39, 32), (1, 2, 3, 4))
• Given a Tuple. Sort tuples by maximum element in a tuple.
Input : test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
Output : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)]
Explanation : 19 > 7 = 7 > 2, is order, hence reverse sorted
by maximum element.
Tuple comprehension
powers = tuple(2**n for n in range(0,10))
print(powers)
Output
(1, 2, 4, 8, 16, 32, 64, 128, 256, 512)

a=[1,2,3,25,30,35,42,49,8,7]
b=(num for num in a if num>20 and num<50)
print(b)
Output
[25,30,35,42,49]
Set
⚫Set is an unordered collection of data type that is iterable,
mutable and has no duplicate elements.
⚫ Sets can be created by using the built-in set() function as
well as by placing the sequence inside curly braces { },
separated by ‘comma’.
⚫ A set contains only unique elements but at the time of
set creation, multiple duplicate values can also be passed.
⚫ The order of elements in a set is undefined and is
unchangeable.
⚫ Type of elements in a set need not be the same, various
mixed-up data type values can also be passed to the set.
SET Methods
❑ add () – Adds an item to the set (Note: As sets don’t have repeating values, the item
that is to be added to a set must not be already a member of the set.)
❑ clear () – Removes all items of the set
❑ difference () – Returns a set with all elements of the invoking set but not of the
second set
❑ intersect () – Returns an intersection of two sets
❑ union () – Returns a union of two sets
❑ Remove()-removes an element from the set
❑ Discard()-discards an element from the list
❑ issubset()- checks whether a subset of another set
❑ issuperset- checks whether a superset of another set
❑ Len () – Gives out the total length of some
❑ max () – Returns the biggest value from a
❑ min () – Returns the smallest value from a
❑ Zip()-returns an iterator of set
❑ Sum()-returns sum of elements
❑ Set()-constructs and returns a set
❑ While using discard() if the item does not exist in the set, it remains
unchanged. But remove() will raise an error in such condition.
# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)
# Creating a Set with the use of a String
set1 = set(“Collegeofengineering")
print("Set with the use of String: ")
print(set1)
# Creating a Set with the use of a List
set1 = set([“College", “Of", “College“])
print("Set with the use of List: ")
print(set1)
# Creating a Set with a mixed type of values (Having numbers and strings)
set1 = set([1, 2, 'Geeks', 4, ‘Tuesday', 6, ‘Monday'])
print("Set with the use of Mixed Values")
print(set1)

Output:
Initial blank Set:
set()
Set with the use of String:
{‘M’,’f’,’C’,’o’,’e’,’n’,’g’,’i’,’n’,’l’,’r’}

Set with the use of List:


{‘Of’,’College}

Set with the use of Mixed Values


{1, 2, 4, 6, ‘Monday', ‘Tuesday'}
Adding Elements to a Set
Elements can be added to the Set by using built-in add() function.
Only one element at a time can be added to the set by using add()
method.

# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)
# Adding element and tuple to the Set
[Link](8)
[Link](9)
[Link]((6, 7))
print("Set after Addition of Three elements: ")
print(set1)
Output:
Initial blank Set:
set()
Set after Addition of Three elements:
{8, 9, (6, 7)}
Accessing a Set
Set items cannot be accessed 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.

# Creating a set
set1 = set(“Hello“,”All”,”Hello”)
print("Initial set")
print(set1)
# Accessing element using for loop
print("Elements of set: ")
for i in set1:
print(i, end =" ")
# Checking the element using in keyword
print(“All" in set1)
Output:
Initial set:
{‘All', ‘Hello'}
Elements of set:
All
Hello
True
⚫ Removing elements from a set
Elements can be removed from the Set by using built-in remove() function but a KeyError arises
if element doesn’t exist in the set. To remove elements from a set without KeyError, use
discard(). Pop() function can also be used to remove and return an element from the set, but it
removes only the first element.

# Creating a Set
set1 = set(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
print("Initial Set: ")
print(set1)
# Removing elements from Set using Remove() method
[Link](5)
[Link](6)
print("Set after Removal of two elements: ")
print(set1)
# Removing elements from Set using Discard() method
[Link](8)
[Link](9)
print("Set after Discarding two elements: ")
print(set1)
# Removing element from the Set using the pop() method
[Link]()
print("Set after popping an element: ")
print(set1)
# Removing all the elements from Set using clear() method
[Link]()
print("Set after clearing all the elements: ")
print(set1)

Output:
Initial Set:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
Set after Removal of two elements:
{1, 2, 3, 4, 7, 8, 9, 10, 11, 12}
Set after Discarding two elements:
{1, 2, 3, 4, 7, 10, 11, 12}
Set after popping an element:
{2, 3, 4, 7, 10, 11, 12}
Set after clearing all the elements:
set()
Set
A = {1,difference
2, 3, 4} method
B = {2, 3, 9}
c=[Link](B)
print(c)
d=[Link](A)
print(d)
Output
(1,4)
(9)
Set
A = {1,Intersection
2, 3, 4} Method
B = {2, 3, 9}
c=[Link](B)
print(c)
d=[Link](A)
print(d)
Output
{2,3}
{2,3}
Union
A Method
= {1, 2, 3, 4}
B = {2, 3, 9}
c=[Link](B)
print(c)
d=[Link](A)
print(d)
Output
{1,2,3,4,9}
{1,2,3,4,9}
A = {1, 2, 3, 4}
Subset and superset methods
B = {2, 3}
c=[Link](B)
print(c)
d=[Link](A)
print(d)
c=[Link](B)
print(c)
d=[Link](A)
print(d)
Output
False
True
True
False
A = {1, 2, 3, 4}
B = {2, 3, 9}
print(A&B) #Intersection
print(A|B) #Union
print(A-B) #difference
Print(B-A) #difference
print(A^B) #Either- - Or
Output
{2,3}
{1,2,3,4}
{1,4}
{9}
{1,4,9}
Set comprehension
A={s for s in [1, 2, 1, 0]}
Print(A)
Output
{0, 1, 2}
B= {s **2 for s in [1, 2, 1, 0]}
print(B)
Output
{0, 1, 4}
Exercises
• Check whether a given string is Heterogram or not. A heterogram is a word,
phrase, or sentence in which no letter of the alphabet occurs more than once.
Input : S = "the big dwarf only jumps" Output : Yes Each alphabet in the string S is
occurred only once. Input : S = "geeksforgeeks" Output : No Since alphabet 'g', 'e',
'k', 's' occurred more than once.

• Managers={“Amol”,”Soham”,”Samarth”,”Shlok”,”Rohan”}
• Engineers={“Rohan”,”Soham”,”Nitin”,”Aditya”}
• Find out the persons who are only engineers
• Find out the persons who are managers as well as engineers
• Find out the persons who are only managers
• Find out the persons who are either engineers or managers
Dictionary
⚫ Unlike other Data Types that hold only single value as an element, Dictionary
holds key:value pair.
⚫ Key-value is provided in the dictionary to make it more optimized. Each key-value
pair in a Dictionary is separated by a colon :, whereas each element is separated
by a ‘comma’.
⚫ Dictionary can be created by placing a sequence of elements within curly {}
braces, separated by ‘comma’.
⚫ Values in a dictionary can be of any datatype and can be duplicated, whereas
keys can’t be repeated and must be immutable.
⚫ Dictionary can also be created by the built-in function dict(). An empty dictionary
can be created by just placing curly braces{}.
⚫ Note – Dictionary keys are case sensitive, same name but different cases of Key
will be treated distinctly.
Dictionary Methods
clear() :- Removes all the elements from the dictionary
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
values() :- Returns a list of all the values in the
dictionary
▪ Len()- returns number of key-value pairs
▪ Max()- returns maximum key value
▪ Min()- returns minimum key value
▪ In & not in -to check existence of any element
▪ Sorted()-Obtain sorted list of keys
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict = {1: ‘Abc', 2: ‘Xyz', 3: ‘Lmn'}
print("Dictionary with the use of Integer Keys: ")
print(Dict)
Dict = {'Name': ‘Abc', 1: [1, 2, 3, 4]}
print("Dictionary with the use of Mixed Keys: ")
print(Dict)
Dict = dict({1: ‘Abc', 2: ‘Xyz', 3:‘Lmn'})
print("Dictionary with the use of dict(): ")
print(Dict)
Dict = dict((1, ‘Abc'), (2, ‘Xyz'))
print("Dictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: ‘Abc', 2: ‘Xyz', 3: ‘Lmn'}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': ‘Abc'}
Dictionary with the use of dict():
{1: ‘Abc', 2: ‘Xyz', 3: ‘Lmn'}
Dictionary with each item as a pair:
{1: ‘Abc', 2: ‘Xyz'}
Adding elements to a Dictionary
One value at a time can be added to a Dictionary by
defining value along with the key e.g.
Dict[Key] = Value
Dict = {}
Dict[0] = ‘Abc'
Dict[2] = ‘Xyz'
Dict[3] = 1
print("Dictionary after adding 3 elements: ")
print(Dict)
Dict[2] = 'Welcome'
print("Updated key value: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: ‘Abc', 2: ‘Xyz', 3: 1}
Updated key value:
{0: ‘Abc', 2: 'Welcome', 3: 1}
Accessing elements from a Dictionary
In order to access the items of a dictionary refer to its key name. Key can be
used inside square brackets. There is also a method called get() that will also
help in accessing the element from a dictionary.

Dict = {1: ‘Abc', 'name': ‘Xyz', 3: ‘Lmn'}


print("Accessing a element using key:")
print(Dict['name'])
print("Accessing a element using get:")
print([Link](3))

Output:
Accessing a element using key:
Xyz
Accessing a element using get:
Lmn
Removing Elements from Dictionary
Using del keyword, specific values from a dictionary can be deleted. Other functions
like pop() can also be used for deleting specific values. All the items from a
dictionary can be deleted at once by using clear() method.

Dict = { 5 : 'Welcome', 6 : 'To', 7 : ‘Abc', 'A' : {1 : ‘Abc', 2 : ‘Xyz', 3 : ‘Lmn'},


'B' : {1 : ‘Hello', 2 : 'Life'}}
[Link]()
print("Deleting the last element ")
print(Dict)
[Link](5)
print("Popping specific element: ")
print(Dict)
[Link]()
print("Deleting Entire Dictionary: ")
print(Dict)
Output:
Deleting the last element
{ 5 : 'Welcome', 7 : ‘Abc', 'A' : {1 : ‘Abc', 2 : ‘Xyz', 3 : ‘Lmn'}}
Popping specific element:
{6 : 'To‘,7: ‘Abc',A': {1: ‘Abc', 2: ‘Xyz', 3: ‘Lmn’}
Deleting Entire Dictionary:
{}
Dictionary comprehension
d={'a':1,'b':2,'c':3,'d':4,'e':5}
d1={k:v**3 for (k,v) in [Link]()}
print(d1)
d2={k:v for(k,v) in [Link]() if v>3}
print(d2)
d3={k:('even' if v%2==0 else 'odd’) for (k,v) in
[Link]()}
print(d3)
Output
{'a':1,'b':8,'c':27,'d':64,'e':125}
{'d':4,'e':5}
{'a':'odd','b':'even','c':'odd','d':'even','e':'odd'}
Nested Dictionary
square_dict = {num: num*num for num in range(1, 11)}
print(square_dict)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
*Nested Dictionary
dictionary = {k1: {k2: k1 * k2 for k2 in range(1, 6)} for k1 in range(2, 5) }
print(dictionary)
Output
{2: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10},
3: {1: 3, 2: 6, 3: 9, 4: 12, 5: 15},
4: {1: 4, 2: 8, 3: 12, 4: 16, 5: 20}}
Assignments
•Write a Python program to count the occurrences of each word in a given
sentence.
a="the color of the sky is blue and the color of the water is also blue“
•Output
{'the':4,'color':2,'of':2,'sky':1,'is':2,'blue':2,'and':1,'water':1,'also':1}
•Python program to find common elements in three lists using sets
•Write a Python program to calculate average of dictionary values and insert
it into the dictionary.
[{'id': 1, 'subject': 'math', 'V': 70, 'VI': 82, 'V+VI': 76},
{'id': 2, 'subject': 'math', 'V': 73, 'VI': 74, 'V+VI': 73.5},
{'id': 3, 'subject': 'math', 'V': 75, 'VI': 86, 'V+VI': 80.5}]
•Write a Python program to find the list of words that are longer than n from
a given list of words.
•Program to divide a list into small equal size chunks

You might also like