This presentation is all about various built in
datastructures which we have in python.
List
Dictionary
Tuple
Set
and various methods present in each data structure
This presentation is all about various built in
datastructures which we have in python.
List
Dictionary
Tuple
Set
and various methods present in each data structure
Regular expressions are used to identify whether a pattern exists in a given sequence of characters (string) or not. They help in manipulating textual data, which is often a pre-requisite for data science projects that involve text mining. You must have come across some application of regular expressions: they are used at the server side to validate the format of email addresses or password during registration, used for parsing text data files to find, replace or delete certain string, etc.
a. Concept and Definition✓
b. Inserting and Deleting nodes ✓
c. Linked implementation of a stack (PUSH/POP) ✓
d. Linked implementation of a queue (Insert/Remove) ✓
e. Circular List
• Stack as a circular list (PUSH/POP) ✓
• Queue as a circular list (Insert/Remove) ✓
f. Doubly Linked List (Insert/Remove) ✓
For more course related material:
https://github.com/ashim888/dataStructureAndAlgorithm/
Personal blog
www.ashimlamichhane.com.np
2D array in C++ language ,define the concept of c++ Two-Dimensional array .with example .and also Accessing Array Components concept.and Processing Two-Dimensional Arrays.
METHODS DESCRIPTION
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.
Textbook Solutions refer https://pythonxiisolutions.blogspot.com/
Practical's Solutions refer https://prippython12.blogspot.com/
Contiguous memory locations are occupied to store data in memory, this structure of storing data is Array.
Introduction to Lists
Elementary Data Representation Different data structures, Operations on Data structures.
Regular expressions are used to identify whether a pattern exists in a given sequence of characters (string) or not. They help in manipulating textual data, which is often a pre-requisite for data science projects that involve text mining. You must have come across some application of regular expressions: they are used at the server side to validate the format of email addresses or password during registration, used for parsing text data files to find, replace or delete certain string, etc.
a. Concept and Definition✓
b. Inserting and Deleting nodes ✓
c. Linked implementation of a stack (PUSH/POP) ✓
d. Linked implementation of a queue (Insert/Remove) ✓
e. Circular List
• Stack as a circular list (PUSH/POP) ✓
• Queue as a circular list (Insert/Remove) ✓
f. Doubly Linked List (Insert/Remove) ✓
For more course related material:
https://github.com/ashim888/dataStructureAndAlgorithm/
Personal blog
www.ashimlamichhane.com.np
2D array in C++ language ,define the concept of c++ Two-Dimensional array .with example .and also Accessing Array Components concept.and Processing Two-Dimensional Arrays.
METHODS DESCRIPTION
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.
Textbook Solutions refer https://pythonxiisolutions.blogspot.com/
Practical's Solutions refer https://prippython12.blogspot.com/
Contiguous memory locations are occupied to store data in memory, this structure of storing data is Array.
Introduction to Lists
Elementary Data Representation Different data structures, Operations on Data structures.
Data processing is an integral part of most modern software development. Understanding of Abstract Algebra and Category theory will be beneficial for addressing data processing concerns.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
The Art Pastor's Guide to Sabbath | Steve ThomasonSteve Thomason
What is the purpose of the Sabbath Law in the Torah. It is interesting to compare how the context of the law shifts from Exodus to Deuteronomy. Who gets to rest, and why?
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
How to Create Map Views in the Odoo 17 ERPCeline George
The map views are useful for providing a geographical representation of data. They allow users to visualize and analyze the data in a more intuitive manner.
This is a presentation by Dada Robert in a Your Skill Boost masterclass organised by the Excellence Foundation for South Sudan (EFSS) on Saturday, the 25th and Sunday, the 26th of May 2024.
He discussed the concept of quality improvement, emphasizing its applicability to various aspects of life, including personal, project, and program improvements. He defined quality as doing the right thing at the right time in the right way to achieve the best possible results and discussed the concept of the "gap" between what we know and what we do, and how this gap represents the areas we need to improve. He explained the scientific approach to quality improvement, which involves systematic performance analysis, testing and learning, and implementing change ideas. He also highlighted the importance of client focus and a team approach to quality improvement.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
2. List and Dictionary in Python (Syllabus)
Lists: list operations - creating, initializing, traversing and
manipulating lists, list methods and built-in functions.
len(), list(), append(), extend(), insert(), count(), index()
remove(), pop(), reverse(), sort(), sorted(), min(), max(), sum()
Dictionary: concept of key-value pair, creating, initializing,
traversing, updating and deleting elements, dictionary methods
and built-in functions.
len(), dict(), keys(), values(), items(), get(), update(), clear(),
del()
1
Sangita Panchal
3. • A list is a sequence of comma separated values (elements/objects) enclosed
in square brackets [].
• The values in a list may be of different types (integer, float, string, list, tuple
etc.) – Heterogeneous data type.
• Lists are mutable i.e. values in a list can be edited /changed.
Sangita Panchal
List – Creating and Initializing list
L1 = [] #Empty list
L1 = [‘English’, 45, ‘Maths’, 86, ‘Rajesh’, 1234]
L2 = [12, 15, ‘Manish’, [45, 87], 23] #Nested List
L3 = [‘Sonia’, (‘E001’, ‘D001’), 34000] # Tuple within a list
L = [1,"abc",(23,12),[23,"str"],{1:"A",2:"B"}]
# number, string, tuple, list, dict
2
4. List items can be accessed by using their index or indices
Sangita Panchal
Accessing List by Index
Forward
Index
Backward
Index
L = ["Eng",65,"Maths",97, "Sc.",89]
print(L[3])
print(L[1+4])
print(L[2*2])
print(L[5-4+1])
97
89
Sc.
Maths
3
5. Slicing
[ start index : end index : step ]
The default of start index is 0, step is 1. It will display data from
start index to end-1 index.
Sangita Panchal
Accessing List - Slicing
L = ["Eng",65,"Maths",97, "Sc.",89]
print(L[ :4])
print(L[2: ])
print(L[ : ])
print(L[ : :-1])
['Eng', 65, 'Maths', 97]
['Maths', 97, 'Sc.', 89]
['Eng', 65, 'Maths', 97, 'Sc.', 89]
[89, 'Sc.', 97, 'Maths', 65, 'Eng']
4
6. Sangita Panchal
Change data in the list
L = ["Eng",65,"Maths",97, "Sc.",89]
print(L)
L[1] = 90
print(L)
L[2:4] = ['IP',99]
print(L)
L[1:3] = [ ]
print(L)
['Eng’, 65, 'Maths', 97, 'Sc.', 89]
['Eng', 90, 'Maths', 97, 'Sc.', 89]
['Eng', 90, 'IP', 99, 'Sc.', 89]
['Eng', 99, 'Sc.', 89]
5
7. Sangita Panchal
List operations – Concatenation
A = [12, 43]
B = [34, 78]
C = A + B
print("C = ",C)
A = A + B
print("A = ",A)
B += A
print("B = ",B)
C = [12, 43, 34, 78]
A = [12, 43, 34, 78]
B = [34, 78, 12, 43, 34, 78]
A = [12, 43]
A = A + 5
TypeError: can only
concatenate list (not "int")
to list
Concatenation: It takes ‘+’ operator to concatenate with another list.
6
Correct
A = [12,43]
A = A + [5]
8. Sangita Panchal
List operations – Repetition
L = [12, 43]
print(L * 2)
L1 = [1,"Amit"]
print(3 * L1)
[12, 43, 12, 43]
[1, 'Amit', 1, 'Amit', 1, 'Amit']]
L = [12, 43]
L2 = [3]
print(L * L2)
TypeError: can't multiply
sequence by non-int value
Repetition: It takes ‘*’ operator to repeat the list content by the
given number.
7
9. Sangita Panchal
List operations –Membership
L = [12, 43]
L1 = [1,"Amit"]
print("Amit" in L1)
print(12 not in L)
True
False
Membership: It check whether the given element is present in
the list or not. It uses
in : The given element is present.
not in: The given element is not present.
8
10. Sangita Panchal
Traversing a List
L = [12,"Amit",[23,43,29]]
for i in L:
print(i, end = " ")
print()
for i in range(len(L)):
print(L[i],end = " ")
12 Amit [23, 43, 29]
12 Amit [23, 43, 29]
9
There are two ways to traverse the list.
1. Element / Member
2. Index – 0, 1, …len(L) - 1
11. Sangita Panchal
Traversing a List – To add number five to each element in
the list.
L = [12, 43, 17, 34, 29]
print("Initial list is: ", L)
print("After adding 5: ", end = "")
for i in range(len(L)):
L[i] += 5
print(L)
Initial list is: [12, 43, 17, 34, 29]
After adding 5: [17, 48, 22, 39, 34]
10
12. Sangita Panchal
List methods – len(), append(), extend()
L = [14,32,29]
L1 = [22,25]
print(L,len(L))
L.append(L1)
print(“After append”,L,len(L))
L = [14,32,29]
print(L,len(L))
L1 = [22,25]
L.extend(L1)
print(“After extend”,L,len(L))
[14, 32, 29] 3
After append [14, 32, 29, [22, 25]] 4
[14, 32, 29] 3
After extend [14, 32, 29, 22, 25] 5
11
append(): It adds the object as one element.
extend(): It adds the elements in the object as
individual element in the list.
13. Sangita Panchal
List methods – count(),insert(),remove()
L = [14,32,29,28,32,14,28]
print(L)
print("Count of 14: ",L.count(14))
L.insert(3,14)
print(L)
print("Count of 14: ",L.count(14))
L.remove(14)
L.remove(14)
print(L)
print("Count of 14: ",L.count(14))
[14, 32, 29, 28, 32, 14, 28]
Count of 14: 2
[14, 32, 29, 14, 28, 32, 14, 28]
Count of 14: 3
[32, 29, 28, 32, 14, 28]
Count of 14
12
count(): It counts the given data present in the list.
insert(): It inserts the data at a given location in the list.
remove(): It removes the given data in a list, whichever comes first from the left to right.
14. Sangita Panchal
List methods – reverse(), sort()
L = [14,32,29,28,12,24]
print(L)
L.reverse()
print("List in reverse order:",L)
L.sort()
print("List in ascending order:",L)
L.sort(reverse = True)
print("List in descending order:",L)
[14, 32, 29, 28, 12, 24]
List in reverse order:
[24, 12, 28, 29, 32, 14]
List in ascending order:
[12, 14, 24, 28, 29, 32]
List in descending order:
[32, 29, 28, 24, 14, 12]
reverse(): it reverses the member in the list.
sort(): It sorts the data in the list in ascending order.
sort(reverse = True): it sorts the data in the list in descending order.
Note: In sort(), it works with homogeneous data type.
13
15. Sangita Panchal
List methods – sort() in string data type
L = ["Zen","Ben","Arif","Kity"]
print("Original list", L,sep = ‘n’)
L.sort()
print("List in Ascending order",L,sep = ‘n’)
L.sort(reverse = True)
print("List in Descending order",L,sep = ‘n’)
Original list
['Zen', 'Ben', 'Arif', 'Kity']
List in Ascending order
['Arif', 'Ben', 'Kity', 'Zen']
List in Descending order
['Zen', 'Kity', 'Ben', 'Arif']
14
16. Sangita Panchal
List methods – sort() in nested list
L = [[23,12],[34,45],[22,11]]
print("Original list", L,sep = ‘n’))
L.sort()
print("List in Ascending order",L,sep = ‘n’)
L.sort(reverse = True)
print("List in Descending order",L,sep = ‘n’))
Original list
[[23, 12], [34, 45], [22, 11]]
List in Ascending order
[[22, 11], [23, 12], [34, 45]]
List in Descending order
[[34, 45], [23, 12], [22, 11]]
15
17. Sangita Panchal
List methods – sort() vs sorted
L = [12,9,5,2,3]
print("Original list", L)
L1 = sorted(L)
print("List in Ascending order",L1)
L1 = sorted(L,reverse = True)
print("List in Descending order",L1)
Original list [12, 9, 5, 2, 3]
List in Ascending order [2, 3, 5, 9, 12]
List in Descending order [12, 9, 5, 3, 2]
16
18. Sangita Panchal
List methods – sort() vs sorted
L = ["Zen","Ben","Arif","Kity"]
print("Original list", L, sep = ‘n’)
L1 = sorted(L)
print("List in Ascending order",L1,sep = ‘n’)
L1 = sorted(L,reverse = True)
print("List in Descending order",L1,sep = ‘n’)
17
Original list
['Zen', 'Ben', 'Arif', 'Kity']
List in Ascending order
['Arif', 'Ben', 'Kity', 'Zen']
List in Descending order
['Zen', 'Kity', 'Ben', 'Arif']
19. Sangita Panchal
List methods – pop(), del
L = [14,32,29,28,12,24]
print(L)
print("Remove the -1 index value:“)
L.pop() ; print(L)
print("Remove the 2 index value:“)
L.pop(2) ; print(L)
print("Remove the 1 index value:“
del L[1] ; print(L)
print("Delete the entire list")
del L ; print(L)
[14, 32, 29, 28, 12, 24]
Remove the -1 index value:
24
[14, 32, 29, 28, 12]
Remove the 2 index value:
29
[14, 32, 28, 12]
Remove the 1 index value:
[14, 28, 12]
Delete the entire list
NameError: name 'L' is not defined12]
18
pop(): It deletes the element mentioned as index. The default index is -1.
del : It deletes the element mentioned as index, otherwise it deletes the entire list
permanently.
20. Sangita Panchal
List methods – index()
L = [14,32,29,32,12,24]
print(L)
print("Index of 32 from left",end ="")
print(L.index(32))
print("Index of 32 after index 2",end ="")
print(L.index(32,2))
print("Index of 40 not present",end ="")
print(L.index(40))
[14, 32, 29, 32, 12, 24]
Index of 32 from left 1
Index of 32 after index 2 3
Index of 40 not present
ValueError: 40 is not in list
19
21. Sangita Panchal
List built-in functions – min(),max(),sum()
L = [14,32,29,32,12,24]
print(L)
print("Maximum:",max(L))
print("Minimum:",min(L))
print("Sum:",sum(L))
print("Average:",round(sum(L)/len(L),2))
[14, 32, 29, 32, 12, 24]
Maximum: 32
Minimum: 12
Sum: 143
Average: 23.83
20
max(): It returns the maximum value in the list.
min(): it returns the minimum value in the list.
sum(): it returns the sum of all the values in the list.
Note: min(), max() works with number or string data type.
sum() works with number data type only.
22. Sangita Panchal
Program 1: To input how many marks, enter marks and
display the average mark.
n = int(input("Enter no. of marks"))
L = []
for i in range(n):
marks = int(input("Enter marks"))
L.append(marks)
s = 0
for i in L:
s += i
print("Average mark", s/n)
Enter no. of marks5
Enter marks23
Enter marks19
Enter marks22
Enter marks15
Enter marks20
Average mark 19.8
21
23. Sangita Panchal
Program 2: To input number of marks, enter marks, search whether
the given mark is present at location or not.
L = []
n = int(input("How many numbers"))
for i in range(n):
n = int(input("Enter number"))
L.append(n)
num = int(input("Enter the number
to be searched: "))
pos = -1
for i in range(n):
if L[i] == num: pos = i ; break
if pos == -1 : print("Number",num,"is not present")
else: print("Number",num,"is present at",pos, "position")
How many numbers5
Enter number21
Enter number23
Enter number20
Enter number17
Enter number19
Enter the number to be searched: 20
Number 20 is present at 2 position
22
24. Sangita Panchal
Program 3: A menu driven program of list, to do the following:
1. Add a data
2. Insert a data
3. Add list
4. Modify data by index
5. Delete by value
6. Delete by position
7. Sort in ascending order
8. Sort in descending order
9. display list
23
25. Sangita Panchal
L = []
while True:
print("""1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display""")
choice = int(input("Enter the choice"))
if choice == 1:
n = int(input("Enter data"))
L.append(n) ; print(L)
elif choice == 2:
n = int(input("Enter data"))
pos = int(input("Enter position"))
L.insert(pos,n) ; print(L)
elif choice == 3:
nList = eval(input("Enter the list to be appended: "))
L.extend(nList) ; print(L)
24
26. Sangita Panchal
elif choice == 4:
i = int(input("Enter the data position to modified: "))
if i < len(L):
num = eval(input("Enter the new element: "))
L[i] = num
else:
print("Position not in the list")
print(L)
elif choice == 5:
i = int(input("Enter the element position to be deleted: "))
if i < len(L):
num = L.pop(i)
else:
print("nPosition not in the list")
print(L)
25
27. Sangita Panchal
elif choice == 6:
num = int(input("nEnter the element to be deleted: "))
if num in L:
L.remove(num)
else:
print("nElement",element,"is not present in the list")
elif choice == 7:
L.sort()
elif choice == 8:
L.sort(reverse = True)
elif choice == 9:
print("nThe list is:", L)
else:
print("Exit")
break
26
28. Sangita Panchal
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice1
Enter data18
[18]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice2
Enter data23
Enter position0
[23, 18]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
Enter the choice3
Enter the list to be appended: 25,21,20
[23, 18, 25, 21, 20]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice4
Enter the data position to modified: 2
Enter the new element: 15
[23, 18, 15, 21, 20]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice5
Enter the element position to be deleted: 1
[23, 15, 21, 20]
27
29. Sangita Panchal
28
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice6
Enter the element to be deleted: 21
[23, 15, 20]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice7
[15, 20, 23]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice8
[23, 20, 15]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice9
The list is: [23, 20, 15]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice10
Exit
31. Sangita Panchal
Dictionary in Python
A dictionary is a mutable object that can store any number of Python
objects. It falls under mapping – a mapping between a set of keys
with corresponding values.
The items are separated by comma and the entire dictionary is
enclosed in curly braces.
Each item consists of two parts – key and a value, separated by a
colon (:).
Keys are unique in dictionary. They must be of an immutable data
types such as strings, numbers or tuples.
The values may have duplicate values. They can be of any data
type.
30
33. Sangita Panchal
Creating an Empty Dictionary
D = {}
print("D = ",D)
D1 = dict()
print("D1 = ",D1)
Two ways to create an empty dictionary
D = {}
D1 = {}
32
34. Sangita Panchal
Accessing Items in a Dictionary
D = {'Amit':56,'Joe':32}
print(D)
print("The value of Joe:",D['Joe'])
print("The value of Amit:" D['Amit'])
The items of the dictionary are accessed via the keys rather than
the index. Each key treated as an index and map with the value.
{'Amit': 56, 'Joe': 32}
The value of Joe: 32
The value of Amit: 56
33
35. Sangita Panchal
Membership operation in a Dictionary
D = {'Amit':56,'Joe':32}
print(D)
print("Check for Amit:",'Amit' in D)
print("Check for Seema:",'Seema' in D)
print("Check of Joe not present",'Joe' not in D)
The membership operator (in) checks whether the key is present in
a dictionary or not. It returns True or False.
{'Amit': 56, 'Joe': 32}
Check for Amit: True
Check for Seema: False
Check of Joe not present False
34
36. Sangita Panchal
Adding /Modifying the item in a Dictionary
D = {'Amit':56,'Joe':32}
print(D)
D['Amit'] = 100
D['Seema'] = 78
print("The updated dictionary")
print(D)
As dictionary is mutable, you can add an item or modify the value
of an already existing key in a dictionary.
{'Amit': 56, 'Joe': 32}
The updated dictionary
{'Amit': 100, 'Joe': 32, 'Seema': 78}
35
37. Sangita Panchal
Traversing a Dictionary
D = {'Amit':56,'Joe':32,'Sid':45}
for key in D:
print(key,":",D[key])
You can traverse a dictionary using for loop. There are two ways to
do the traversing.
Amit : 56
Joe : 32
Sid : 45
D = {'Amit':56,'Joe':32,'Sid':45}
for key,value in D.items():
print(key,":",value)
Amit : 56
Joe : 32
Sid : 45
36
38. Sangita Panchal
Built-in functions and methods in Dictionary – len(), update()
D = dict() ; print(D,len(D))
D1 = {'Amit':56,'Joe':32,'Sid':45}
D.update(D1)
print(D,len(D))
D2 = {'Joe':43,'Jia':47}
D.update(D2) ; print(D,len(D))
{} 0
{'Amit': 56, 'Joe': 32, 'Sid': 45} 3
{'Amit': 56, 'Joe': 43, 'Sid': 45, 'Jia': 47} 4
dict(): It creates and empty dictionary.
len(): It returns the number of items in the dictionary.
update(): If key is present, it updates the value, otherwise, adds the
item in the dictionary.
37
39. Sangita Panchal
Built-in functions and methods in Dictionary –
keys(),values(),items()
D = {'Amit':56,'Joe':32,'Sid':45,'Jia':47}
print(D.keys())
print(D.values())
print(D.items())
dict_keys(['Amit', 'Joe', 'Sid', 'Jia'])
dict_values([56, 32, 45, 47])
dict_items([('Amit', 56), ('Joe', 32), ('Sid', 45), ('Jia', 47)])
keys(): It returns the list of keys in the dictionary.
values(): it returns the list of values in the dictionary.
items(): It returns the key, value pair in tuple and entire data in list.
38
40. Sangita Panchal
Built-in functions and methods in Dictionary – get()
D = {'Amit':56,'Joe':32,'Sid':45,'Jia':47}
D = {'Amit':56,'Joe':32,'Sid':45}
print(D.get('Sid'))
print(D.get('amit'))
print(D['Sid'])
print(D['amit'])
45
None
45
KeyError: 'amit'
It returns the value corresponding to the passed key, if present;
otherwise it returns None. It is similar to D[key].
39
41. Sangita Panchal
Built-in functions and methods in Dictionary – get()
D = {'Amit':56,'Joe':32,'Sid':45}
del D['Joe']
print(“Aafter deleting Joe“, D)
D.clear()
print(“After deleting content“,D)
del D
print("Permanently deletes the
dictionary“,D)
After deleting Joe {'Amit': 56, 'Sid': 45}
After deleting content {}
Permanently deletes the dictionary
NameError: name 'D' is not defined'
clear(): deletes the entire content leaving empty dict.
del: deletes the specified item or entire dict permanently.
40
42. Sangita Panchal
Write a python program to create a dictionary from a string.
Sample string ‘w3resource’
Expected output {‘3’:1, ‘s’:1, ‘r’:2, ‘u’:1, ‘w’:1, ‘c’:1, ‘e’:2, ‘o’:1}
st = input("Enter a string ")
d = {}
for ch in st:
if ch in d:
d[ch] += 1
else:
d[ch] = 1
print(d)
Enter a string AEOBCAB
{'A': 2, 'E': 1, 'O': 1, 'B': 2, 'C': 1}
41
43. Sangita Panchal
Write a program to convert a number entered by the user into its
corresponding number in words. For example, if the number is 876,
then the output should be ‘Eight Seven Six’
num = input("Enter any number")
d = {0: 'Zero', 1:'One', 2:'Two', 3:'Three', 4:'Four',
5:'Five', 6:'Six', 7:'Seven', 8: 'Eight', 9:'Nine'}
result = ''
for ch in num:
key = int(ch)
value = d[key]
result = result + " " +value
print( result)
Enter any number17439
One Seven Four Three Nine
42
44. Sangita Panchal
Write a program to input your friend’s names and their phone
numbers and store them in the dictionary as the key-value pair.
Perform the following operations on the dictionary:
Display the name and phone number for all your friends.
Add a new key-value pair in this dictionary and display the
modified dictionary.
Enter the name whose phone number you want to modify. Display
the modified dictionary.
Enter the friend’s name and check if a friend is present in the
dictionary or not.
Display the dictionary in sorted order of names.
43
45. Sangita Panchal
D = {}
while True:
print("1 create/add, 2 modify, 3 search, 4 sort, 5 exit")
choice = int(input("Enter choice"))
if choice == 1:
while True:
name = input("Enter your name ")
phone = input("Enter your phone number")
D[name] = phone
choice = input("Continue Y/N")
if choice.upper() == "N":
break
print(D)
44
46. Sangita Panchal
elif choice == 2:
n = input("Enter the name whose phone number
you want to modified")
flag = 0
for i in D.keys():
if i == n:
p = input("Enter the modified phone number")
D[i] = p ; flag = 1 ; break
if flag == 0: print("Name not found")
print("The dictionary is = ", D)
45
47. Sangita Panchal
elif choice == 3:
n = input("Name")
flag = 0
for i in D.keys():
if i == n: print("Present") ; flag = 1 ; break
if flag == 0: print("Name Not present")
elif choice == 4:
for key,value in sorted(D.items()):
print(key,":",value,end = ",")
elif choice == 5: print("End of program");break
else: print("Enter correct choice")
46
48. Sangita Panchal
47
1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice1
Enter your name samy
Enter your phone number2134
Continue Y/Ny
Enter your name joe
Enter your phone number4343
Continue Y/Nn
{'samy': '2134', 'joe': '4343'}
1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice2
Enter the name whose phone number you want to modifiedjoe
Enter the modified phone number1111
The dictionary is = {'samy': '2134', 'joe': '1111'}
1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice3
Namesamy
Present
1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice4
joe : 1111,samy : 2134,1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice5
End of program