String Material
String Material
Note: Interpreter converts high level language to low level language line by line.
Features of Python:
Easy: Python is simple and easy to learn and code. Its syntax is almost English-like.
Expressive: Easy syntax and fewer syntactical constructions make python an expressive language.
Free and open source: Python is a free and open-source language, as you can download and
install it in your computer without paying any fee.
High-level Language: Python is a high-level language because it has all the features of a high-level
language. Its English-like syntax makes it easy to read and write. It is easy to find errors and debug
Python programs.
Portable: Python is a platform-independent language. Python programs can run on any platform
without making any changes to them.
Object Oriented: Python supports object-oriented programming (OOP) principles such as
encapsulation (bundling of data (attributes) and methods (functions)), inheritance (inheriting the
properties and behaviours of an existing class (base class or superclass)), and polymorphism (take
multiple forms). Everything in Python is an object, which allows for modular and reusable code.
Interpreted: Python uses an interpreter (Known as Python Virtual Machine) to convert the code
and run on any platform.
Extensive Libraires: The Python Libraries is a collection of functions that you can add in your
program. It helps to make Python programs simple and easy.
Dynamically-Typed Language: Python is dynamically typed language. It means you do not need to
declare the type of variables before their use while programming.
Uses of Python:
Python is used in many domains as listed below:
1. Web and Internet Development: Python has huge built in library that supports internet
protocols and offers many choices for web development.
2. Scientific and Numeric Computing: Python is widely used to compute scientific and numeric
problems as it has a huge library of mathematics and data analysis packages.
3. Desktop GUIs: Python is also used to build desktop GUIs and applications using various toolkits.
4. Software Development: Software developers are using python to develop various tools and
software.
5. Business Applications: Python is used to build ERP (Enterprise Resource Planning) and e-
commerce systems that can be used with huge data and can solve complex problems.
Python Installation: Python can be directly downloaded and installed from the website:
[Link]
Execution Modes of Python:
There are Two ways to use the python interpreter:
1. Interactive mode (Python IDLE (Integrated Development and Learning Environment)):
In the interactive mode, we can simply type a python statement on the >>> prompt directly. As
soon as we press enter, the interpreter executes the statement and displays the result/s. This mode
is convenient for testing a single line code for instant execution. But in the interactive mode, we
cannot save the statements for future use and we have to retype the statements to run them again.
2. Script Mode: In the script mode, we can write a python program in a file, save it and then use
the interpreter to execute it. Python files has an extension “.py”. To execute the python program in
script mode click Run→ Run Module from menu or press F5 from the keyboard.
Python Terminology.
Keywords: Keywords are reserved words, each keyword has a specific meaning to the python
interpreter, and we can use a keyword in our program only for the purpose for which it has been
defined.
Examples: if, elif, do, while, print, not in, in…….
Identifiers: Identifiers are names used to identify a variable, function or other entities in a program.
The naming conventions of identifiers in python are as follows.
1. An identifier cannot start with a digit.
2. Keywords cannot be used as identifiers.
3. We cannot use special symbols like! @, #, $, %.... etc as identifiers. (Only underscore is allowed)
Examples of valid identifiers.
1. num1
2. percentage
3. student_mark
Examples of invalid identifiers.
1. 1_num
2. marks@grade11
3. pass
Variables: Variable in python refers to an object- an item or element that is stored in the memory.
Value of a variable can be a
String: ‘b’, ‘global citizen’
Numeric: 123
Alphanumeric:CD123
Variable declaration is implicit in python, which means variables are automatically declared and
defined when they are assigned a value for the first time. Variables must always be assigned values
before they are used in expressions otherwise it will lead to an error in the program.
Example1: Write a program to store the names of three students and display them.
Method1: Script Mode Aman
name1="Aman" Amit
name2="Amit" Sumit
name3="Sumit"
print(name1)
print(name2)
print(name3)
Method2: Interactive Mode
>>> name1="Aman"
>>> name2="Amit"
>>> name3="Sumit"
>>> print(name1)
Aman
>>> print(name2)
Amit
>>> print(name3)
Sumit
>>>
Example 2: Write a program to display the sum of two numbers:
Method1: Script Mode 50
num1=20
num2=30
s=num1+num2
print(s)
Method2: Interactive Mode
>>> num1=20
>>> num2=30
>>> s=num1+num2
>>> print(s)
50
>>> print(num1+num2)
50
Comments: Comments are used to add a remark or note in the source code. Comments are not
executed by interpreter. They are added with the purpose of making the source code easier for
humans to understand. In python, a comment starts with # (Hash Sign)
Chapter-5
String Manipulation
Handout
String: In Python, a string is a sequence of characters or symbols enclosed within single quotes (')
or double quotes ("). It is a fundamental data type used to represent textual data.
Creating Python Strings: As long as the same sequence of characters is enclosed, single or double
or triple quotes don't matter. Hence, following string representations are equivalent.
Example:
>>> 'Welcome To PES Public School'
'Welcome To PES Public School '
>>> "Welcome To PES Public School
'Welcome To PES Public School
>>> '''Welcome To PES Public School '''
'Welcome To PES Public School '
>>> """Welcome To PES Public School"""
'Welcome To PES Public School'
A string stores all the elements in memory and assigns an index value or position -id to it, which
can be used to access its individual characters.
In python, the string data type is an ordered sequence of character data. Elements of a string can
be accessed by using index vales.
The process of storing and retrieving elements of an ordered data type using index or key values
is called INDEXING.
Index values are numeric, either positive or negative.
Characters of a string are held in continuous memory locations. These memory locations are
indicated by indices.
For example, consider the string msg=’BOTTLE’ and observe the location of its elements in the
memory.
Positive
0 1 2 3 4 5
Indexing
List
B O T T L E
Elements
Negative
-6 -5 -4 -3 -2 -1
Indexing
Square brackets [] can be used to access characters of the string. Individual characters in a string
can be accessed by specifying the string name followed by its index number in the square
brackets [].
Accessing Values in Strings: Python does not support a character type; these are treated as
strings of length one, thus also considered a substring.
To access substrings, use the square brackets for slicing along with the index or indices to obtain
your substring.
For example:
var1 = 'Hello World!' Output:
var2 = "Python Programming" var1[0]: H
print ("var1[0]: ", var1[0]) var2[1:5]: ytho
print ("var2[1:5]: ", var2[1:5])
Repetition - Creates new strings, concatenating multiple copies a*2 will give -
*
of the same string HelloHello
Slice - Gives the character from the given index a[1] will give
[]
e
Range Slice - Gives the characters from the given range a[1:4] will give
[:]
ell
Membership - Returns true if a character does not exist in the M not in a will
not in given string give
1
Raw String - Suppresses actual meaning of Escape characters. print r'\n' prints
The syntax for raw strings is exactly the same as for normal \n and print
strings with the exception of the raw string operator, the letter R'\n'prints \n
r/R
"r," which precedes the quotation marks. The "r" can be
lowercase (r) or uppercase (R) and must be placed immediately
preceding the first quote mark.
fname=input("Enter your first name ") Enter your first name Ravi
lname=input("Enter your last name ") Enter your last name Kiran
print(fname+' '+lname) Ravi Kiran
Note: Concatenation operations can only be performed on strings.
Repetition: A string can be repeated a specific number of times using the repetition operator (*).
The * operator makes multiple copies of a sequence and joins them together. The * operator is
also called the multiplication operator, which is used to multiply two numeric values and display
the result. On String, it acts differently and multiplies the sequence with given number of times.
For example,
fname=input("Enter your first name ") Enter your first name Ravi
lname=input("Enter your last name ") Enter your last name Kiran
print(("Welcome" +fname+' '+lname)*5) WelcomeRavi KiranWelcomeRavi
KiranWelcomeRavi KiranWelcomeRavi
KiranWelcomeRavi Kiran
Using Membership Operators: Membership operators are used to test the presence of an element
in a string. There are two types of membership operators.
1. “in” operator: The membership operator ‘in’ is used to check if a value exists in a sequence or
not. If it finds the element in the sequence, then it returns True, otherwise it will return False.
2. ‘not in’ operator: The not in operator returns True if it does not find the element in sequence,
otherwise it returns False.
Example:
Slicing: A slice means ‘a part of’ something. Similarly, python allows you to fetch a substring from
a string. A substring or a part of string can be accessed by using the slicing operator colon (:).
An expression of the form s[m:n] returns the substring or a part of the string S starting with index
m, and display up to n-1( not including the character at index n).
Example:
Slicing Output
print(s[-5]) O
print(s[:-5]) H
print(s[::-1]) tsenoH
print(s[-3:-1]) es
print(s[-1:-6:-2]) teo
Program-4: Write a program that obtains a string from the user and displays it in reverse order.
fruit='orange' o
index=0 r
while index<len(fruit): a
c=fruit[index] n
print(c) g
index=index+1 e
String Built-in-Functions: Python has a wide range of built-in functions or methods that can be
used with strings.
1. len(): python len() function can be used to find the length of a given string. It takes the name of
the string as a parameter and returns the length of the string as a numeric value.
Syntax: len(string)
Example:
name='guido van rossum'
l=len(name)
print(l)
output: 16
2. capitalize(): This function converts the first letter of the string to a capital letter.
Syntax: [Link]()
If there is a single element in a tuple then the element should be followed by a comma, otherwise
it will be treated as integer instead of tuple. For example
>>> a=(2) >>> b=(2,)
>>> type(a) >>> type(b)
<class 'int'> <class 'tuple'>
Accessing Elements in a Tuple: Elements of a tuple can be accessed in the same way as a list
or string using indexing and slicing. For example
>>>a=(‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’)
Positive 0 1 2 3 4 5 6 7
Indexing
Elements C O M P U T E R
Negative -8 -7 -6 -5 -4 -3 -2 -1
Indexing
Tuple is immutable:
Tuple is an immutable data type. It means that the elements of a tuple cannot be changed after it
has been created. For example:
a=('c', 'o', 'm', 'p', 'u', 't', 'e', 'r')
>>> a[2]='s'
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
a[2]='s'
TypeError: 'tuple' object does not support item assignment
Tuple Operations:
1. Concatenation: Joining of two or more tuples is called concatenation. Python allows us to join
tuples using concatenation operator (+)
Example:
>>>t1=(1,2,3)
>>>t2=(8,9,10)
>>>t1+t2
Output:
(1,2,3,8,9,10)
2. Repetition (*): It is used to repeat elements of a tuple.
>>>h1=(‘H’, ‘M’)
>>>h1*3
Output:
('H', 'M', 'H', 'M', 'H', 'M')
3. Membership: The ‘in’ operator checks the presence of element in tuple. If the element is
present, it returns True, else it returns False.
The not in operator returns True if the element is not present in the tuple, else it returns False.
Example:
>>>h1=(‘H’, ‘M’)
>>>’H’ in h1
Output:
True
>>>’m’ not in h1
True
4. Slicing: It is used to extract one or more elements from the tuple. Like string and list, slicing
can be applied to tuples also.
Example:
>>>t1=(1,2,3,7,8,9)
>>>t1[2:4]
(3,7)
>>>t2=(10,20,30,40,50,60,70,80)
>>>t1[2:7]
(30,40,50,60,70)
>>>t1[:5]
(10,20,30,40,50)
>>>t1[::-1]
(80,70,60,50,40,30,20,10)
Built-in Function:
1. len(): This method returns the length of tuple or the number of elements in the tuple.
>>>t1=(10,20,30,40,50,60,70,80)
>>>len(t1)
8
2. tuple(): This function creates an empty tuple or creates a tuple if a sequence is passed as
argument.
>>>t1=tuple()
>>>type(t1)
Output: <class 'tuple'>
>>>t2=tuple(‘python’)
>>> type(t2)
<class 'tuple'>
>>>t3=('p', 'y', 't', 'h', 'o', 'n')
>>>t3=tuple([1,2,3])
>>>t3
(1,2,3)
>>>t4=tuple(range(7))
>>>t4
(0,1,2,3,4,5,6)
3. count(): This function returns the frequency of an element in the tuple.
>>>t1=tuple(“tuple in python”)
>>>[Link](‘p’)
2
4. index(): This function returns the index of the first occurrence of the element in the given
tuple.
>>>t1=tuple(“tuples in python”)
>>>[Link](‘n’)
8
>>>t1=tuple(“tuples in python”)
>>>[Link](‘f’)
Output: ValueError: [Link](x): x not in tuple
5. sorted(): This element takes tuple as an argument and return a sorted list. This function does
not make any change in the original tuple.
>>>t1=(‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
>>>sorted(t1)
Output: [‘e’, ‘l’, ‘p’, ‘s’, ‘t’, ‘u’]
6. min(): This function returns minimum or smallest element of the tuple.
>>>t1=(3,8,4,10,1)
>>>min(t1)
1
7. max(): This function returns maximum or largest element of the tuple.
>>>t1=(3,8,4,10,1)
>>>max(t1)
10
>>>t1=(‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
>>>max(t1)
U
8. sum(): This function returns sum of the elements of the tuple.
>>>t1=(3,8,4,10,1)
>>>sum(t1)
26
Tuple Assignment: It allows a tuple of variables on the left side of the assignment operator to be
assigned respective values from a tuple on the right side. The number of variables on the left should
be same as the number of elements in the tuple. For example,
>>>(n1,n2)=(5,9)
>>>print(n1)
5
>>>print(n2)
9
>>>(a,b,c,d)=(5,6,8)
ValueError: not enough values to unpack (expected 4, got 3)
Nested Tuple: A tuple inside another tuple is called a nested tuple. In nested tuple we can access
the elements in the same way of nested list. For example,
>>>t1=((“Amit”, 90), (“Sumith”, 75), (“Ravi”, 80))
>>>t1[0]
(“Amit”, 90)
>>>t1[1][1]
75
43. Write a program to remove a number (accepted from the user) from the given tuple
T1=(12,15,18,21,24,27,30)
Note: Sample Execution
Enter element to remove:21
Tiple after removing element is: (12,15,18,24,27,30)
T1=(12,15,18,21,24,27,30) enter the number to be removed:30
el=int(input("enter the number to be (12, 15, 18, 21, 24, 27)
removed:"))
if el in T1:
L=list(T1)
[Link](el)
T1=tuple(L)
print(T1)
else:
print("Element not found")
44. What do you mean by Unpacking Tuple? Give Example.
Answer: Creating/Initializing individual variables from the values of tuple is called unpacking.
For example,
T1=(2,4,6)
X,y,z=T1
print(x)
print(y)
print(z)
Output:
2
4
6
45. What do you mean by Packing Tuple? Give Example
Answer: Creating a tuple from individual values is called packing tuple. For example,
T1=2,4,6
46. Write one similarity between Tuples and String.
Answer: Tuples and Strings are immutable; means we cannot edit values in a Tuple and String.
47. Write the output of the following:
>>>T1=(2,’Apple’,6)
>>>print(max(T1))
Answer: TypeError: '>' not supported between instances of 'str' and 'int'
48. Consider the given tuple and write the output of given statements: T1=(1,23,4,5,
“A”,[“C”, “D”],(23,45), 45)
[Link](len(T1))
2. print([Link](45))
3. print([Link](45))
4. print(T1[5][0]*2)
5. print(T1[:])
6. print(T1[5:])
7. Print([Link](“A”))
8. print(T1[-1:-7:-2])
9. print(T1[4]+T1[5])
10. print(max(T1))
Chapter-8
Dictionary in Python
Dictionary: A python dictionary is a collection of elements where each element is a combination
of Key-Value pair. Each value/s is associated with a unique key. All the Key-Value pairs are
enclosed in curly braces. In other words, we can say that “Dictionaries are mutable, unordered
collection of elements in the form of Key-Value pairs which are enclosed in curly braces”.
Note: In Python 3.5 and before, iterating over a dict would return keys in arbitrary order. The order
of iteration would not match the order in which the items were inserted. Starting with python 3.6
and above versions, dictionaries will preserve insertion order.
Example:
1. A={1: “one”, 2: “Two”, 3: “Three”}
2. B={“A”: “Apple”, “B”: “Ball”, “C”: “Cat”}
3. B={"A": "Apple", "B": "Ball", "B": "Cat"}
>>>B
{'A': 'Apple', 'B': 'Cat'}
Dictionary A has numeric Keys (1,2,3) and Values (“One”, “Two”, “Three”) are in string, while
dictionary B has both keys(‘A’, ‘B’, ‘C’) and Values (“Apple”, “Ball”, “Cat”) are in string.
Q2: Write a program to store book id, book name and price of three books and store the
data in dictionary named “dict”.
dict={} Enter Book ID: 1
for i in range(3): Enter Book Name: Python
b_id=int(input("Enter Book ID: ")) Enter Book Price: 499
b_name=(input("Enter Book Name: ")) Enter Book ID: 2
b_price=int(input("Enter Book Price: ")) Enter Book Name: Java
temp=[b_name,b_price] #temporary list Enter Book Price: 399
dict[b_id]=temp Enter Book ID: 3
print(dict) Enter Book Name: AI with Python
Enter Book Price: 589
{1: ['Python', 499], 2: ['Java', 399], 3: ['AI with
Python', 589]}
Adding Elements to Dictionary: you can add new elements (key:value pair) to a dictionary
using assignment as per the following syntax. But the key added must not exist in dictionary and
must be unique. If the key is already exists, then this statement will change the value of existing
key and no new entry will be added to dictionary.
Syntax: <dictionary>[<key>]=<value>
Example:
>>> B={1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
>>> B['8']='Harini'
>>> B
{1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi', '8': 'Harini'}
Appending value in Python Dictionary: We can add new element in dictionary by the
following way.
Example:
A={1: 'one', 2: 'Two', 3: 'Three'}
A[4]= “Four”
print(A)
Output:
{1: 'one', 2: 'Two', 3: 'Three', 4: 'Four'}
Example:
A={1: 'one', 2: 'Two', 3: 'Three'}
B={“A”: “Apple”, “B”: “Ball”, “C”: “Cat”}
[Link](B)
print(A)
Output:
{1: 'one', 2: 'Two', 3: 'Three', 'A': 'Apple', 'B': 'Ball', 'C': 'Cat'}
Note: It over writes the values of same keys and add the values of different keys.
Example:
A={1: 'one', 2: 'Two', 3: 'Three'}
B={1: 'Four', 2: 'Five', 3: 'Six', 4: 'Seven'}
[Link](B)
print(A)
Output:
{1: 'Four', 2: 'Five', 3: 'Six', 4: 'Seven'}
Update values in a python Dictionary: We cannot change the key of an element, but can
change the value of a respective key as follows.
Example:
B A={'A': 'Apple', 'B': 'Ball', 'C': 'Cat'}
A['B’] = 'Banana'
print(A)
Output:
{'A': 'Apple', 'B': 'Banana', 'C': 'Cat'}
Removing an element from a dictionary: There are two ways by which we can delete the
elements of dictionary.
2. By using pop() function: This function not only delete the element of required key but also
return the deleted value.
>>> B={1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
>>> a=[Link](2)
>>> print(a)
>>> print(B)
Sunil
{1: 'Amit', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
Checking for Existence of a key: Usual membership operators ‘in’ and ‘not in’ work with
dictionaries as well. But they can check for the existence of keys only.
To use a membership operator for a key’s presence in a dictionary, you may write statement as
per syntax given below:
Pretty Printing a Dictionary: To pretty print a dictionary in Python, you can use the ‘json’
module, which stands for " JavaScript Object Notation." This will display the dictionary with a nicer
formatting, especially useful when dealing with nested dictionaries or dictionaries with long values.
Alternatively, you can also use [Link]() with indent parameter to achieve pretty printing.
[Link](): The main purpose of [Link]() is to serialize Python objects into a JSON
formatted string. This means converting a Python object (such as a dictionary or a list) into a string
representation in the JSON format.
Example:
B={1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
import json
print([Link](B, indent=2))
Output:
{
"1": "Amit",
"2": "Sunil",
"5": "Lata",
"6": "Suman",
"7": "Ravi"
}
Split(): the split() function is a built-in method used to split a string into a list of substrings based
on a specified delimiter.
Syntax: [Link](separator)
separator (optional): The delimiter string based on which the splitting is performed. If not
provided, the default delimiter is whitespace (space, tab, newline).
Example:1
>>> text = "Hello world! This is a sentence."
>>> words = [Link]()
>>> print(words)
['Hello', 'world!', 'This', 'is', 'a', 'sentence.']
Example:2
>>> text="One, Two Three, Four, Five"
>>> word=[Link](',')
>>> print(word)
['One', ' Two Three', ' Four', ' Five']
Accessing Items, Keys and Values: get(), items(), keys(), values() methods can access
individual, values, all items, keys and values of the dictionary using the following methods.
<dict>.get() # to get values of the given key
<dict>.items() # to get all the items of the dictionary
<dict>.keys() # to get all the keys of the dictionary
<dict>.values # to get all the values of the dictionary
The get() method: It is used to get the value of the given key. It accepts two parameters. The
first is key and the second is default arguments. The default argument contains an error message
if the key is not present in the dictionary.
>>> d={'Virat':45,'Rehane':56,'Pujara':76,'Rahul':34}
>>> print([Link]('Virat'))
45
>>> print([Link]('Sachin','Not Found'))
Not Found
>>> print([Link]('Sachin'))
None
items(): It is used to get the items presents in the dictionary as a sequence of (key, value) tuples.
d={'Virat':45,'Rehane':56,'Pujara':76,'Rahul':34}
l=[Link]()
for i in d:
print(i)
Output:
Virat
Rehane
Pujara
Rahul
keys(): This method returns all the keys of a dictionary in a list form. It will not follow any
particular order. Observe this example:
d={'Ramesh':15000,'Suresh':20000,'Akhilesh':21000,'Sameer':22000}
print([Link]())
Output:
dict_keys(['Ramesh', 'Suresh', 'Akhilesh', 'Sameer'])
values(): It will return values in list form from the dictionary. Just take a look at this:
d={'Ramesh':15000,'Suresh':20000,'Akhilesh':21000,'Sameer':22000}
print([Link]())
Output:
dict_values([15000, 20000, 21000, 22000])
Creating Dictionary from keys- the fromkeys() method: The fromkeys() method is used to
create a new dictionary from a sequence containing all the keys and a common value, which will
be assigned to all the keys.
Syntax: [Link](<key sequence>, [<value>])
Where the method name is to be used as [Link] and:
<key sequence> is a python sequence containing the keys for the new dictionary.
<value> is the common value that will be assigned to all the keys; if skipped, value None is
assigned to all the keys.
Example:
>>> A=[Link]([2,4,6,8],100)
>>> A
{2: 100, 4: 100, 6: 100, 8: 100}
>>> A=[Link]([2,4,6,8])
>>> A
{2: None, 4: None, 6: None, 8: None}
>>> A=[Link](3)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
A=[Link](3)
TypeError: 'int' object is not iterable
>>> A=[Link](3,)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
A=[Link](3,)
TypeError: 'int' object is not iterable
>>> A=[Link]((3,))
>>> A
{3: None}
>>> A=[Link]([3])
>>> A
{3: None}
Extend/Update Dictionary with new key:value pairs: update() and setdefault()
methods.
We can extend or update a dictionary by adding or updating a single key:value pair to an existing
dictionary or we can add/update key:value pairs from another dictionary, using the following
methods.
1. The setdefault() method: The setdefault() method inserts a new key:value pair ONLY IF the
key doesn’t already exist. If the key already exists, it returns the current value of the key. You can
use this method as: [Link](<key>,<value>)
Where <key> and <value> are the key and value to be added to the dictionary, if <value> is not
passed as input, the default none value is used as the value.
1. If the given key is NOT ALREADY PRESENT in the dictionary, it will add the specified
new key:value pair to the dictionary and return the value of the added key.
2. If the key is ALREADY PRESENT in the dictionary, the dictionary will not be updated, but
the current value associated to the specified key is returned.
>>> [Link](5,320)
320
>>> marks
>>> [Link](5,340)
320
>>> marks
{1: 350, 2: 423, 3: 411, 4: 300, 5: 320}
Note: If we only provide a key without any value and the key does not exist in the dictionary, it
will take none as the value.
>>> [Link](6)
>>> marks
2. The update() method: This method merges key:value pairs from the new dictionary into the
original dictionary, adding or replacing as needed. The items in the new dictionary are added to
the old one and override any items already there with the same keys.
Example:
>>> [Link](Employee2)
>>> Employee1
>>> Employee2
Making Shallow copy of a Dictionary: The copy() method of dictionaries creates a shallow
copy of dictionary.
(i) Shallow copy, where only the upper layer is copied and inner referenced object is not copied.
<dict>.copy()
Where, <dict> is the dictionary to be copied, -returns a shallow copy of the dictionary.
Example:
>>> Employee3=[Link]()
>>> Employee3
>>> Employee2
(ii) Deep copy, where all the layers are recursively copied and even inner referenced objects are
copied.
Example:
>>> Q= {'1': {'Name': 'Anusha'}, '2': ['Name', 'Harini']}
>>> import copy
>>> W = [Link](Q)
>>> W
{'1': {'Name': 'Anusha'}, '2': ['Name', 'Harini']}
>>> Q
{'1': {'Name': 'Anusha'}, '2': ['Name', 'Harini']}
Working of Copy:
Case-1: Creating copy using assignment operator: When we assign a dictionary name to
another name using assignment operator =, it does not create a copy internally. It will just make
two labels reference the same dictionary. Thus, any changes in either of the name will be reflected
in the other label.
>>> d={'Ramesh':15000,'Suresh':20000,'Akhilesh':21000,'Sameer':22000}
>>> d1=d
>>> d1
{'Ramesh': 15000, 'Suresh': 20000, 'Akhilesh': 21000, 'Sameer': 22000}
>>> d
{'Ramesh': 15000, 'Suresh': 20000, 'Akhilesh': 21000, 'Sameer': 22000, 'Anil': 23000}
>>> d1['Anil']=23000
>>> d1
{'Ramesh': 15000, 'Suresh': 20000, 'Akhilesh': 21000, 'Sameer': 22000, 'Anil': 23000}
>>> d
{'Ramesh': 15000, 'Suresh': 20000, 'Akhilesh': 21000, 'Sameer': 22000, 'Anil': 23000}
Note: Making changes with any label will change the same dictionary and will be reflected
through both the labels.
Case-II: Creating copy using the copy() method: When we create a copy of a dictionary
using , copy() , a copy of keys is created with the new name and the values referenced are shared
by two copies.
→ If the VALUES referenced by the keys are immutable, then any changes made in the copy
created with copy() will not be reflected in the original dictionary.
Example:
>>> stu={1:'Sneha',2:'Neha',3:'Anusha'}
>>> Stu2=[Link]()
>>> stu
{1: 'Sneha', 2: 'Neha', 3: 'Anusha'}
>>> Stu2
{1: 'Sneha', 2: 'Neha', 3: 'Anusha'}
>>> Stu2[4]='Harini'
>>> stu
{1: 'Sneha', 2: 'Neha', 3: 'Anusha'}
>>> Stu2
{1: 'Sneha', 2: 'Neha', 3: 'Anusha', 4: 'Harini'}
→ If the values referenced by the keys are mutable (such as list), then the keys will be
referring to the same python list objects (i.e., the memory addresses of the values won’t change)
but lists being mutable can change.
Example:
>>> d1={1:[1,2,3],2:[3,4,5]}
>>> d2=[Link]()
>>> d1
{1: [1, 2, 3], 2: [3, 4, 5]}
>>> d2
{1: [1, 2, 3], 2: [3, 4, 5]}
>>> d2[1].append(4)
>>> d1
{1: [1, 2, 3, 4], 2: [3, 4, 5]}
>>> d2
{1: [1, 2, 3, 4], 2: [3, 4, 5]}
>>> d2[2].append(6)
>>> d1
{1: [1, 2, 3, 4], 2: [3, 4, 5, 6]}
>>> d2
{1: [1, 2, 3, 4], 2: [3, 4, 5, 6]}
>>> d1[1].append(5)
>>> d1
{1: [1, 2, 3, 4, 5], 2: [3, 4, 5, 6]}
>>> d2
{1: [1, 2, 3, 4, 5], 2: [3, 4, 5, 6]}
1. pop(): This method removes and returns the dictionary element associated to passed key. The
pop() method will not only delete the key:value pair for mentioned key but also return the
corresponding value.
Syntax: <dict>.pop(key,<value>)
Example:
>>> Stu2
{1: 'Sneha', 2: 'Neha', 3: 'Anusha', 4: 'Harini'}
>>> [Link](2)
'Neha'
>>> Stu2
{1: 'Sneha', 3: 'Anusha', 4: 'Harini'}
>>> [Link](5)
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
[Link](5)
KeyError: 5
>>> [Link](5, 'No such key')
'No such key'
Note: with pop() we can specify your own return value in the form of a message or a value, in case
the given key is not found in the dictionary but with del statement, if the key is not in the dictionary,
it will raise the error.
2. popitem(): The popitem() removes and returns a (key,value) pair from the dictionary.
(i) It returns the last item entered in the dictionary.
(ii) The items will be removed from the dictionary in the LIFO (Last In First Out) order.
(iii) It returns the deleted key:value pair in the form of a tuple.
(iv) If the dictionary is empty, calling popitem() raises a KeyError.
Syntax: <dict>.popitem()
Where, <dict> is the name of the dictionary, and it returns the deleted key:value pair as tuple.
Example:
>>> stu
{1: 'Sneha', 2: 'Neha', 3: 'Anusha'}
>>> [Link]()
(3, 'Anusha')
>>> stu
{1: 'Sneha', 2: 'Neha'}
3. clear(): This method removes all items from the dictionary and the dictionary becomes empty.
Syntax: <dict>.clear()
Note: clear() method takes no arguments.
Example:
>>> [Link]()
>>> stu
{}
Get sorted list of keys: The sorted() function considers only the keys of the dictionary for
sorting and returns a sorted list of the dictionary keys.
Syntax: sorted(<dict>,[reverse=False])
Where,
<dict> name of the dictionary whose keys are to be sorted.
[reverse] argument is optional and when set to True, it will return the keys of the dictionary sorted
in descending order, default value of reverse is False.
Example:
>>> d={'Ramesh':15000,'Suresh':20000,'Akhilesh':21000,'Sameer':22000}
>>> f=sorted(d)
>>> f
['Akhilesh', 'Ramesh', 'Sameer', 'Suresh']
>>> e=sorted(d, reverse=True)
>>> e
['Suresh', 'Sameer', 'Ramesh', 'Akhilesh']
>>> g=sorted([Link]())
>>> g
['Akhilesh', 'Ramesh', 'Sameer', 'Suresh']
>>> g=sorted([Link]())
>>> g
[15000, 20000, 21000, 22000]
>>> h=sorted([Link]())
>>> h
[('Akhilesh', 21000), ('Ramesh', 15000), ('Sameer', 22000), ('Suresh', 20000)]
>>> d1={(1,2):'One',(3,4):'Two'}
>>> sorted(d1)
[(1, 2), (3, 4)]
Calculating Maximum, Minimum and Sum: Like lists and tuples, we can apply the max(), min(),
sum() functions on dictionaries too.
Syntax:
max(<dict>)
min(<dict>)
sum(<dict>)
Example:
>>> Stu2
{1: 'Sneha', 3: 'Anusha', 4: 'Harini'}
>>> min(Stu2)
1
>>> max(Stu2)
4
>>> sum(Stu2)
8
NOTE:
Difference between a Dictionary, Tuple and List
List Tuple Dictionary
A list is a sequence. A tuple is a sequence. A dictionary is a hash table of
key-value pair.
List is an ordered collection of Tuple is an ordered collection Dictionary is an unordered
items. of items collection.
List is mutable, i.e., it is Tuple is immutable. Addition Dictionary is mutable, i.e., it is
possible to add a new item or or deletion operations are not possible to add a new item or
delete an item from it. possible on tuple object delete an item from it.
List items are enclosed in Tuple items are enclosed in Dictionary items are enclosed
square brackets []. round brackets or parentheses in curly brackets {}.
().
List items are indexed. Tuple items are indexed. Items in dictionary are not
indexed.
Programs
1. Write a python program to arrange the values in a dictionary in ascending order.
Answer:
>>> d={1:21, 2:32, 3:25}
>>> print(sorted([Link]()))
[21, 25, 32]
>>> print(d)
{1: 21, 2: 32, 3: 25}
2. Write a python program to join/merge/concatenate the following two dictionaries
and create the new dictionary.
d1={1:'Amit',2:'Suman'} d2={4:'Ravi',5:'Kamal'}
Answer:
d1={1:'Amit',2:'Suman'} {1: 'Amit', 2: 'Suman', 4: 'Ravi', 5: 'Kamal'}
d2={4:'Ravi',5:'Kamal'}
d3={}
for i in (d1,d2):
[Link](i)
print(d3)
3. Write a function check(key) which takes a key as an argument and check whether
that key is present in dictionary or not.
Answer:
d1={1:'Amit',2:'Suman'} Key is present
def check(i):
for k in d1:
if k==i:
print("Key is present")
break
else:
print("Key is not present")
check(1)
4. Accept the number of terms say n from the user and display the dictionary in the
form of {n:n*5} for example:
If number of terms entered by user is 4 then the expected dictionary is
{1:5,2:10,3:15,4:20}
Answer:
d1={} Enter any number3
n=int(input("Enter any number")) {1: 5, 2: 10, 3: 15}
for i in range(n): Enter any number6
d1[i+1]=(i+1)*5 {1: 5, 2: 10, 3: 15, 4: 20, 5: 25, 6: 30}
print(d1)
5. Write a program to add the values of given dictionary.
d1={1:2, 2:90,3:50}
Answer:
>>> d1={1:2, 2:90,3:50}
>>> print(sum([Link]()))
142
6. Write a program to add keys of given dictionary.
d1={1:2, 2:90,3:50}
Answer:
>>> d1={1:2, 2:90,3:50}
>>> print(sum([Link]()))
6
7. Write a program to multiply all the values of given dictionary. d1={1:2, 2:90,3:50}
Answer:
d1={1:2, 2:90,3:50} 6
s=1
for i in d1:
s=s*i
print(s)
8. Write a program to accept a key from the user and remove that key from the
dictionary if present.
d1={1:2,2:90,3:50} Enter any key5
k=int(input("Enter any key")) Key not found
if k in d1: Enter any key3
[Link](k) {1: 2, 2: 90}
print(d1)
else:
print("Key not found")
9. Write a program in python to display the maximum and minimum value in
dictionary.
Answer:
d1={1:21,2:90,3:50} Maximum Value is 90
mx=max([Link]()) Minimum Value is 21
mn=min([Link]())
print("Maximum Value is", mx)
print("Minimum Value is", mn)
10. Write a program in python to remove the duplicate values from the dictionary as
per the following example.
Original Dictionary= d1={1:"Aman", 2:"Suman", 3:"Aman"}
New Dictionary={1: 'Aman', 2: 'Suman'}
Answer:
d1={1:"Aman", 2:"Suman", 3:"Aman"} {1: 'Aman', 2: 'Suman'}
nd1={}
for k,v in [Link]():
if v not in [Link]():
nd1[k]=v
print(nd1)
11. Write a program to count the number of elements in a dictionary.
Answer:
d1={1:"Aman", 5
2:"Suman",3:"Aman",4:"Amit",5:"Sumit"}
print(len(d1))
12. Accept a key from the user to modify its value.
Answer:
d1={1:"Aman",2:"Suman",3:"Aman",4:"Amit",5:"Sumit"} Enter the key1
k=int(input("Enter the key")) Enter the Modified ValueRiyaz
v=input("Enter the Modified Value") {1: 'Riyaz', 2: 'Suman', 3: 'Aman', 4:
d1[k]=v 'Amit', 5: 'Sumit'}
print(d1) Enter the key5
Enter the Modified ValueHarini
{1: 'Aman', 2: 'Suman', 3: 'Aman', 4:
'Amit', 5: 'Harini'}
13. Write a program to store information of products like product id, product name and
product price in a dictionary by taking product id as a key.
Answer:
t=int(input("Enter Number of terms")) Enter Number of terms2
prod={} Enter Product id1
for i in range(t): Enter Product NameNutella
pid=int(input("Enter Product id")) Enter Product Price200
pn=input("Enter Product Name") Enter Product id2
pp=int(input("Enter Product Price")) Enter Product NamePeanut Butter
temp=(pn,pp) Enter Product Price150
prod[pid]=temp {1: ('Nutella', 200), 2: ('Peanut Butter', 150)}
print(prod)
14. Write a program to accept the employee id from the user and display its details
from the dictionary. Data is stored in the dictionary in the following format.
{Empid:(Empname, EmpSalary)}
Answer:
emp={1:("Amit",25000),2:("Suman",30000),3:("Ravi",36000)} Enter the product id1
pid=int(input("Enter the product id")) Employee id, Employee Name
i=[] Salary
if pid in emp: 1 Amit
i=emp[pid] 25000
print("Employee id, Employee Name","\t""Salary")
print(pid,"\t\t",i[0],'\t\t',i[1])
else:
print("Record not found")
15. Write a program to display the name of all the employees whose salary is more than
25000 from the following dictionary.
emp={1:("Amit",25000),2:("Suman",30000),3:("Ravi",36000)}
Format of data is given below:
Answer:
emp={1:("Amit",25000),2:("Suman",30000),3:("Ravi",36000)} Employees whose salary is more
d=list([Link]()) than 25000 is/are
print("Employees whose salary is more than 25000 is/are") Suman
for i in d: Ravi
if i[1]>25000:
print(i[0])
16. Write a program to count the frequency of each word in a given string accepted
from the user using dictionary.
Answer:
str1=input("Enter any String") Enter any StringIndia is my country i love my
w=[Link]() country India
d={} Frequency of India is 2
for i in w: Frequency of is is 1
if i not in d: Frequency of my is 2
d[i]=[Link](i) Frequency of country is 2
for i in d: Frequency of i is 1
print("Frequency of",i,"is",d[i]) Frequency of love is 1
17. Write a program to accept roll number, names and marks of five students and store
the details in dictionary using roll number as key. Also display the sum of marks of all
the five students.
Answer:
d={} Enter roll number1
s=0 Enter NameAmit
for i in range(5): Enter marks25
rn=int(input("Enter roll number")) Enter roll number2
nm=input("Enter Name") Enter NameSumit
mrk=input("Enter marks") Enter marks25
temp=(nm,mrk) Enter roll number3
d[rn]=temp Enter NameHarini
for i in d: Enter marks30
L=d[i] Enter roll number4
s=s+int(L[1]) Enter NameAnusha
print("Sum of Marks ",s) Enter marks27
Enter roll number5
Enter NameTeja
Enter marks20
Sum of Marks 25
Sum of Marks 50
Sum of Marks 80
Sum of Marks 107
Sum of Marks 127
18. Write a program to count the frequency of each character in a given string accepted
form the user using dictionary. (Store the character as key and its frequency as value)
Answer:
str1=input("Enter any string") Enter any stringEngineering
d={} Frequency of E is/are 1
for i in str1: Frequency of n is/are 3
if i not in d: Frequency of g is/are 2
d[i]=[Link](i) Frequency of i is/are 2
for i in d: Frequency of e is/are 2
print("Frequency of",i, "is/are",d[i]) Frequency of r is/are 1