0% found this document useful (0 votes)
3 views

2-Data-Structure

The document provides a comprehensive overview of data structures in Python, particularly focusing on sequences such as lists, tuples, and range objects. It details various operations and methods applicable to lists, including accessing, updating, deleting, and manipulating elements, along with examples for clarity. Additionally, it introduces the concepts of stacks and queues, explaining their operations and characteristics.

Uploaded by

athulatk6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

2-Data-Structure

The document provides a comprehensive overview of data structures in Python, particularly focusing on sequences such as lists, tuples, and range objects. It details various operations and methods applicable to lists, including accessing, updating, deleting, and manipulating elements, along with examples for clarity. Additionally, it introduces the concepts of stacks and queues, explaining their operations and characteristics.

Uploaded by

athulatk6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Data Structures –V Module

Weblink: https://docs.python.org/3.3/tutorial/appetite.html

Complete python documentation with the help of above link

A sequence is a succession of values bound together by a container that reflects their


type. Almost every stream that you put in Python is a sequence.

Sequence (Python) In Python, sequence is the generic term for an ordered set.

There are three basic sequence types: lists, tuples, and range objects.

Operation/Functions & Description


x in seq
True, when x is found in the sequence seq, otherwise
False

x not in seq
False, when x is found in the sequence seq, otherwise
True

x+y
Concatenate two sequences x and y
x * n or n * x
Add sequence x with itself n times

seq[i]
ith item of the sequence.

seq[i:j]
Slice sequence from index i to j

seq[i:j:k]
Slice sequence from index i to j with step k

len(seq)
Length or number of elements in the sequence

min(seq)
Minimum element in the sequence

max(seq)
Maximum element in the sequence

seq.index(x[, i[, j]])


Index of the first occurrence of x (in the index range i
and j)

seq.count(x)
Count total number of elements in the sequence

seq.append(x)
Add x at the end of the sequence

seq.clear()
Clear the contents of the sequence

seq.insert(i, x)
Insert x at the position i

seq.pop([i])
Return the item at position i, and also remove it from
sequence. Default is last element.
seq.remove(x)
Remove first occurrence of item x

seq.reverse()
Reverse the list

Examples:

myList1 = [10, 20, 30, 40, 50]


myList2 = [56, 42, 79, 42, 85, 96, 23]

if 30 in myList1:
print('30 is present')

output
30 is present
**************************************************

if 120 not in myList1:


print('120 is not present')
output
120 is not present
*************************************************

print(myList1 + myList2) #Concatinate lists


output
[10, 20, 30, 40, 50, 56, 42, 79, 42, 85, 96, 23]
**************************************************

print(myList1 * 3) #Add myList1 three times with itself


output
[10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50]
**************************************************

print(max(myList2))
output
96

**************************************************
print(myList2.count(42)) #42 has two times in the list
output
2

**************************************************
print(myList2[2:7])
output
[79, 42, 85, 96, 23]

**************************************************
print(myList2[2:7:2])
output
[79, 85, 23]

**************************************************
myList1.append(60)
print(myList1)
output
[10, 20, 30, 40, 50, 60]

**************************************************
myList2.insert(5, 17)
print(myList2)
output
[56, 42, 79, 42, 85, 17, 96, 23]

**************************************************
myList2.pop(3)
print(myList2)
output
[56, 42, 79, 85, 17, 96, 23]

**************************************************
myList1.reverse()
print(myList1)
output
[60, 50, 40, 30, 20, 10]

**************************************************
myList1.clear()
print(myList1)
output
[]
Weblink: https://docs.python.org/3.3/tutorial/datastructures.html#tuples-and-
sequences

Weblink: https://artofproblemsolving.com/wiki/index.php/Sequence_(Python)

Lists
• It is a sequence in which elements are written as a list of comma separated values
between square brackets.
• The key feature of a list is that it can have elements that belong to different data
types.
The syntax:
List_variable = [ value1, value2]
Example: 1
list_a = [1,2,3,4,5]
print(list_a)
Output: [1, 2, 3, 4, 5]
*******************************************************
Example: 2
list_a = [1,'A',"bcd"]
print(list_a)
Output: [1, 'A', 'bcd']

Access values in Lists:

To access values in lists square brackets are used to slice along with the index or indices
to get value stored at that index.

Syntax:

sequence = list[start:stop:step]

Example: #program to demonstrate the slice operations used to access the elements of
the list.

num_list = [1,2,3,4,5,6,7,8,9,10]
print("num_list is:", num_list)
print("first element in the list is", num_list[0])
print("num_list[2:5]=",num_list[2:5])
print("num_list[::2]=", num_list[::2])
print("num_list[1::3]=", num_list[1::3])
Output:

num_list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


first element in the list is 1
num_list[2:5]= [3, 4, 5]
num_list[::2]= [1, 3, 5, 7, 9]
num_list[1::3]= [2, 5, 8]

Updating Values in lists:

• Updating can be done using assignment operator (=)


• Adding new values can be done by using append () method.
• Deleting can be done by using Del statement.

Example

num_list = [1,2,3,4,5,6,7,8,9,10]

print("num_list is:", num_list) num_list[5]=1000


print("list after updation is:",num_list)

num_list.append(2000)
print("list after appending a value is", num_list)

del num_list[3]
print("list after deleting a value is:",num_list)

Output

num_list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


list after updation is: [1, 2, 3, 4, 5, 1000, 7, 8, 9, 10]
list after appending a value is [1, 2, 3, 4, 5, 1000, 7, 8, 9, 10, 2000]
list after deleting a value is: [1, 2, 3, 5, 1000, 7, 8, 9, 10, 2000]

Example: #program to illustrate deletion of numbers from a list using del statement

num_list = [1,2,3,4,5,6,7,8,9,10] #a list is defined


del num_list[2:3] #deletes numbers at index 2 and 3
print(num_list)

Output: [1, 2, 4, 5, 6, 7, 8, 9, 10]


Example: #program to illustrate deletion of numbers from a list using del statement

num_list = [1,2,3,4,5,6,7,8,9,10] # A list is defined


del num_list[:] # Deletes all the numbers from
the list
print(num_list) # An empty list is printed

Output

[]

Example: #program to insert a list in another list using the slice operation

num_list = [1,2,3,4,5,6,7,8,9,10] # A list is defined


print("original list", num_list)
num_list[3] = [1000,2000,3000]
print("after inserting another list, the updated lis is",num_list)

Output

Original list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


After inserting another list, the updated lis is [1, 2, 3, [1000, 2000, 3000], 5,
6, 7, 8, 9, 10]

Nested Lists

Nested list means a list within another list.

Example: #program to illustrate nested list

num_list = [1,2,3,4,5,6,7,8,9,10, "PYTHON WITH JULIA CALLED 1.2


RELEASED" , [1000,2000,300] , 3.142,4.142,5.142]
i=0
while i<(len(num_list)):
print("num_list[",i,"]=",num_list[i])
i+=1

Output

num_list[ 0 ]= 1
num_list[ 1 ]= 2
num_list[ 2 ]= 3
num_list[ 3 ]= 4
num_list[ 4 ]= 5
num_list[ 5 ]= 6
num_list[ 6 ]= 7
num_list[ 7 ]= 8
num_list[ 8 ]= 9
num_list[ 9 ]= 10
num_list[ 10 ]= PYTHON WITH JULIA CALLED 1.2 RELEASED
num_list[ 11 ]= [1000, 2000, 300]
num_list[ 12 ]= 3.142
num_list[ 13 ]= 4.142
num_list[ 14 ]= 5.142

Cloning Lists

If you want to modify a list and also keep a copy of the original list, then you should
create a separate copy of the list. This process is called cloning.

Example: #Program to create a copy as well as the clone of the original list

list1 = [1,2,3,4,5,6,7,8,9,10]
list2 = list1 #copy is a list using reference
print("list1 =", list1)
print("list2 =", list2) #both lists point to the same list
list3 = list1[2:6]
print("list3=",list3) #list is a clone of list1

Output

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list3= [3, 4, 5, 6]

Basic List Operation:

Some of the list operations are listed below:

Operation Description Example Output

Len Returns length of a Len([1,2,3,4,5,6,7,8]) 8


list
Concatenation Joins a two lists [1,2,3] + [5,6,7] [1,2,3,5,6,7]
Repetition Repeats elements in “Hello”, “World” * [‘Hello’,’World’,
the list 2 [‘Hello’,’World’]
in Checks if the value ‘a’ in True
is present in the list [‘a’,’e’,’i’,’o’,’u’]
not in Checks if the value ‘s’ not in True
is not present in the [‘a’,’e’,’i’,’o’,’u’]
list
max Returns maximum List = [10,50,100] 100
value in the list Print((max(list))
min Returns minimum List = [10,50,100] 10
value in the list Print(min(list))
sum Adds the values in List = [10,50,100] Sum=160
the list that has Print(“sum=”,(list))
numbers
all Returns true if all num_List = [0,1,2,3] False
elements of the list Print(all(list))
are true
any Returns true if any num_list = True
element of the list is [6,3,7,0,1,2,4,9]
true if the list is Print(any(num_list))
empty, returns false
list Converts an list1 = [‘H’,’E’,’L’,’L’,’O’]
iterable(tuple, list(“HELLO”)
string, set, print(list1)
dictionary) to a list
sorted Returns a new List1=[3,4,1,2,7,8] [1,2,3,4,7,8]
sorted list. The List2=sorted(list1)
original list is not Print(list2)
sorted

List Methods:

Some of the methods of list are follows:

Method Description Syntax


Append() Appends an element to the list.append(obj)
list
Count() Counts the number of times list.count(obj)
an element appears in the
list
Index() Returns the lowest index of list.index(obj)
object in the list, gives a
value error object if it’s not
present in the list
Insert() Insert object at the specified list.insert(index,object)
index in the list.
Pop() Removes the element at the list.pop([index])
specified index from the
list.
Remove() Removes or deletes object list.remove(obj)
from the list.
Reverse() Reverse the elements in the list.reverse()
list
Sort() Sorts the elements in the list list.sort()
Extend() Addsthe element in a list to list.extend(list2)
the end of another list,
using + or += on a list is
similar to using extend().

Note: insert (), remove (), sort () methods only modify the list and do not return any
value.

If you print the return values of these methods, you will get none, because a design
principle that is applicable to all mutable data structures in python.

# Program to show the sort mentioned

list1 = ['1','a',"abc",'2','B',"Def"]
list1.sort()
print(list1)

Output
['1', '2', 'B', 'Def', 'a', 'abc']

Note: sort method uses ASCII values to sort the values in the list.

That is upper case letters comes before lowercase and numbers comes even before the
upper case letters.
Using Lists as Stack:

What is Stack?

Stack is a linear data structure which uses the LIFO format (Last in First Out) data
structure, as the element that was inserted last is the first one to be taken out.

Stack supports three basic operations: push, pop and peep (peek)

• Push- this operation adds an element at the end of the stack.


• Pop- this operation removes the last element from the stack.
• Peep- this operation returns the value of the last element of the stack (without
deleting it).

# Progra m to illustrate operations on stack

stack = [1,2,3,4,5,6]
print("Original Stack is:", stack)

stack.append(7)
print("Stack after the push opertion is:", stack)

stack.pop()
print("Stack after the pop operation is:", stack)

last_element_index = len(stack)-1

print("Value obtained after peep operation is:", stack[last_element_index])

Output:

Original Stack is: [1, 2, 3, 4, 5, 6]


Stack after the push operation is: [1, 2, 3, 4, 5, 6, 7]
Stack after the pop operation is: [1, 2, 3, 4, 5, 6]
Value obtained after peep operation is: 6
Using Lists as Queues:

Queue is an important data structure which stores its elements in an ordered manner.

A queue is a FIFO (First in First Out) data structure in which the element that is inserted
in the first is to be taken out.

The elements in a queue are added at one end and removed from the other end.

Queue supports three basic operations: insert, delete, and peep (peek)

• Insert ()-in queue the append () method is used to insert the element at the end of
the queue.
• Delete () - in queue the pop () method used with the index 0 (zero) to delete the
first element from the queue.
• Peep () - the slice operation to print the value of the last element in the queue.

# Program to illustrate operations on queue using list data structure

queue = [1,2,3,4,5,6]
print("Original Stack is:", queue)

queue.append(7)
print("Stack after the push opertion is:", queue)

queue.pop(0)
print("Stack after the pop operation is:", queue)

last_element_index = len(queue)-1

print("Value obtained after peep operation is:",


queue[last_element_index])

Output

Original Stack is: [1, 2, 3, 4, 5, 6]


Stack after the push opertion is: [1, 2, 3, 4, 5, 6, 7]
Stack after the pop operation is: [2, 3, 4, 5, 6, 7]
Value obtained after peep operation is: 7
List Comprehension:

Python supports computed lists called list comprehension.

Syntax: list [expression for variable in sequence]

# Program to make a list of cubes

cubes = [ ] # an empty list


for i in range(11):
cubes.append(i**3) # i=1 (1*1*1=1) or i=2 (2*2*2=8)
print("Cubes of numbers form 1-10:",cubes)

Output

Cubes of numbers form 1-10: [0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

• In list comprehension, the expression is evaluated once for every item in the
sequence.
• List comprehension is also used to create a subsequence of those elements that
satisfy a certain condition.

Example 2

cubes = [i**3 for i in range(10)]


print(cubes)

Output

[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]

Example 3: # Program to combine and print elements of list using list comprehension

print([(x,y) for x in [10,20,30] for y in [30,40,50] if x!=y])

Output

[(10, 30), (10, 40), (10, 50), (20, 30), (20, 40), (20, 50), (30, 40), (30, 50)]
Looping in Lists:

Python’s for and in constructs is extremely useful especially when working with lists.

The for var in list statement is an easy way to access each element in a list.

Syntax: for i in list


print(i)

Example: Using the enumerate () function

• This function is used to when you want print both index as well as an item in the
list.
• The enumerate function object which contains the object and value of all the
items of the list as a tuple.

# Program to illustrate the use of enumerate () to print an individual item and its index
in the list

num_list = [1,2,3,4,5,6,7,8,9,10]

for index, i in enumerate(num_list):


print(i, "is at index:", index)

Output

1 is at index: 0
2 is at index: 1
3 is at index: 2
4 is at index: 3
5 is at index: 4
6 is at index: 5
7 is at index: 6
8 is at index: 7
9 is at index: 8
10 is at index: 9
Tuple:

Creating a Tuple is very simple and can be created using the comma-separated values
within parentheses.

Examples:

tup1 = () #Creating an empty tuple


print(tup1)

tup1 = (5) #Creating an tuple with a single element


print(tup1)

tup1 = (1,2,3,4,5) #Creating an tuple of integers


print(tup1)

tup1 = ('A','B','C','D',) #Creating an tuple of characters


print(tup1)

tup1 = ('SHIV','SHRU','RAJ') #Creating an tuple of strings


print(tup1)

tup1 = (3.142,15.84,22,78) #Creating an tuple of floating point numbers


print(tup1)

tup1 = (1,'SHIV',3.142, 'F') #Creating an tuple of mixed values


print(tup1)

Output:

()
5
(1, 2, 3, 4, 5)
('A', 'B', 'C', 'D')
('SHIV', 'SHRU', 'RAJ')
(3.142, 15.84, 22, 78)
(1, 'SHIV', 3.142, 'F')
If you want create a tuple with a single element, and then you must add a comma after
the element. In the absence of a comma, python treats the element as an ordinary data
type.

Example:

tup1 = (10) #Comma missing


print(type(tup1))

tup1 = (10,) #Comma after the first element


print(type(tup1))

Output:

<class 'int'>
<class 'tuple'>

Accessing Values in a Tuples:

To access values in tuple slice operation used along with the index.

tuple = (10,20,40,30,60,50,70,90,80,100)
print("tuple[:]=",tuple[:])
print("tuple[:5]=",tuple[:5])

Output:

tuple[:]= (10, 20, 40, 30, 60, 50, 70, 90, 80, 100)
tuple[:5]= (10, 20, 40, 30, 60)

Updating Tuple:

Tuple is immutable and so the values(s) in the tuple cannot be changed, you can only
extract values from a tuple to form another tuple.

tuple1 = (10, 20, 40, 30)


tuple2 = (100,200,300,400)
tuple3 = tuple1 + tuple2
print(tuple3)

Output: (10, 20, 40, 30, 100, 200, 300, 400)


Deleting elements in Tuple:

Since tuple is an immutable data structure you cannot delete value(s) from it.

tuple1 = (10,20,40,30)
del tuple1[3]
print(tuple1)

Output

TypeError: 'tuple' object doesn't support item deletion

However, you can always delete the entire tuple by using the Del statement.

tuple1 = (10,20,40,30)
del tuple1
print(tuple1)

Output

NameError: name 'tuple1' is not defined

Note: the name error occurs because; you are now trying to print a tuple that has
already been deleted.

Basic Tuple Operations:

Operation Expression
Length Len((1,2,3,4,5))
Concatenation (1,2,3)+(4,5,6)
Repetition (“GOOGLE”)*3
Membership 5 in (1,2,3,4,5,6,4,7,8,9)
Iteration For i in (1,2,3,4,5,6,4,7,8,9):
Comparison (use >,<, ==) Tup1 = (1,2,3,4,5)
Tup2 = (1,2,3,4,5)
Print(Tup1 > Tup2)
Maximum Max(1,0,3,8,2,9)
Minimum Min(1,0,3,8,2,9)
Tuple Assignment:

Tuple assignment is a very powerful feature in python; it allows a tuple of variable on


the left side of the assignment operator to be assigned values from a tuple given on the
right side of the assignment operator. Each value is assigned to its respective variable.

(val1, val2, val3) = (1,2,3)


print(val1, val2, val3)

Output

123

Example

(val1, val2, val3)= (1,2)


print(val1, val2, val3)

Output

ValueError: not enough values to unpack (expected 3, got 2)

Tuples for Returning Multiple Values:

When we need to return more than one value from a function, in such situation it is
preferable to group together multiple values and return them together.

Example: Program to return the Highest and Lowest values in the list

def max_min(values):
x = max(values)
y = min(values)
return (x,y)

values = (100,45,80,90,15)
(max_marks, min_marks) = max_min(values)

print("Highest marks:=", max_marks)


print("Lowest marks:=",min_marks)

Output: Highest marks: = 100

Lowest marks: = 15
Nested Tuples:

Python allows defining a tuple inside another tuple and this is called nested tuple.

For example, we have a list of players who have topped in their respective sports. We
store the Name, Sport, and Average runs of three players as Tuples inside the tuple
toppers.

topper = (("Yuvraj","Cricket",100),
("Bolt","Running",100),("Dhoni","Cricket",100))
for i in topper:
print(i)

Output

('Yuvraj', 'Cricket', 100)


('Bolt', 'Running', 100)
('Dhoni', 'Cricket', 100)

Checking the Index: index () method:

The index of an element in the tuple can be obtained by using the index ( ) method.

Syntax: list.index (obj)

Where, obj is the object to be found out.

Source Code

stu = ("A","B","C","D")
index = stu.index("D")
print("D is present at index:", index)

Output

D is present at index: 3
Counting the Element: Count () Method

The count () method is used return the number of elements with a specific value in a
tuple.

Example: program to count the number of times letter ‘X’ appears in the specified
string.

Source Code

tuple = "abcdxxxxefghxxxxijklxxxxmnopxxxxqrstxxxxuvwxxxxxyz"
print("x appears",tuple.count('x'),"times in",tuple)

Output

x appears 25 times in
abcdxxxxefghxxxxijklxxxxmnopxxxxqrstxxxxuvwxxxxxyz

The Zip () function:

• The zip () is a built-in function that takes two or more sequences and zips them
into a list of tuples.
• The zip () function is a list of tuples where each tuple contains a character from
the list and an integer from the tuple.
• To perform zip () we should have equal number of values in the list and tuple.

Source Code

value11 = (1,2,3)
value22 = ['A','B','C']
print(list(zip(value11,value22)))

Output

[(1, 'A'), (2, 'B'), (3, 'C')]

Advantages of Tuple over List:

Tuple List
Tuples are used to store values of different Lists are used to store values of same/
data types similar data types
Tuples are immutable Lists are mutable
Tuples can be used as key for a dictionary Lists cannot be used as keys
Tuples are best used for storing data Lists are also used for storing data but in
which is write protected that is data once lists we can change / alter the list.
stored cannot be changed

SETS:

A set () data structure supported by python and it is created using / by placing all the
elements inside the curly brackets { }.

Sets are lists with no duplicates in the final result.

Source Code

#program to convert a list of values into a set

value11 = [1,2,3]
print(set(value11))

Output

{1, 2, 3}

Source Code

#program to convert a list of values into a set with no diplicates


string = "shivshru"
print(set(string))

Output

{'s', 'v', 'u', 'i', 'h', 'r'}

Like in case of mathematical sets, Python supports different operations like:

• Union: Union of two sets includes all elements from both the sets
• Intersection: Intersection of two sets includes elements that are common to both
the sets
• Difference: Difference of set 1 and set 2 includes all elements are in set 1 but not
in set 2.
• Symmetric difference: Symmetric difference of set1 and set2 includes all
elements that are in set1 and set2 but not the one that are common to set1 and
set2.
Source Code

#Program to find intersection, union,difference, symmetric_difference between two


sets

cricket = set(["Dhoni","Yuvraj","Bolt","Sachint","Sganguly"])

analyst= set(["Ravis","Sganguly","Sachint"])
print("=================================================
======================================")
print("cricket:",cricket)
print("---------------------------------------------------------------------------------------")
print("analyst:",analyst)
print("---------------------------------------------------------------------------------------")
print("People playing as cricket's as well as analyst:",
cricket.intersection(analyst))
print("---------------------------------------------------------------------------------------")
print("People playing as cricket's as well as analyst:",
cricket.union(analyst))
print("---------------------------------------------------------------------------------------")
print("People playing as cricket's as well as analyst:",
cricket.difference(analyst))
print("---------------------------------------------------------------------------------------")
print("People playing as cricket's as well as analyst:",
cricket.symmetric_difference(analyst))
print("=================================================
======================================")

Output

======================================================
=================================
cricket: {'Bolt', 'Sachint', 'Dhoni', 'Sganguly', 'Yuvraj'}
---------------------------------------------------------------------------------------
analyst: {'Sganguly', 'Sachint', 'Ravis'}
---------------------------------------------------------------------------------------
People playing as cricket's as well as analyst: {'Sganguly', 'Sachint'}
---------------------------------------------------------------------------------------
People playing as cricket's as well as analyst: {'Dhoni', 'Sganguly', 'Ravis',
'Bolt', 'Sachint', 'Yuvraj'}
---------------------------------------------------------------------------------------
People playing as cricket's as well as analyst: {'Dhoni', 'Bolt', 'Yuvraj'}
---------------------------------------------------------------------------------------
People playing as cricket's as well as analyst: {'Bolt', 'Dhoni', 'Ravis',
'Yuvraj'}
======================================================
=================================

Set Operations:

Operation Description Code Output


a.update(b) Adds elements of set a in a = set([1,2,3,4,5])
the set b provided that all b = set([6,7,8]) {1, 2, 3, 4, 5, 6, 7, 8}
duplicates are avoided a.update(b)
print(a)

a.add(x) Adds element x to the set a = set([1,2,3,4,5])


a provided that all a.add(6) {1, 2, 3, 4, 5, 6}
duplicates are avoided print(a)

a.clear() Removes all elements a = set([1,2,3,4,5]) set()


from the set a.clear()
print(a)

a.remove(x) Removes element c from a = set([1,2,3,4,5]) {1, 2, 4, 5}


set a a.remove(3)
print(a)

len(a) Returns the length of a set a = set([1,2,3,4,5]) 5


print(len(a))

x in a Returns true if x is a = set([1,2,3,4,5]) True


present in set a print(5 in a)

sorted(a) Returns a new sorted list a = {1, 2, 3, 4, 5, 6, 7, 8,


from the elements in the set([1,2,3,4,5,10,8,7,9,6]) 9, 10}
set print(set(sorted(a)))
Dictionaries:

• Dictionary is a data structure in which we store values as a pair of key and value.
• Each key is separated from its value by a colon (:) and consecutive items are
separated by commas.
• The entire items in a dictionary are enclosed in curly brackets { }.

Syntax:

Dictionary_name = {key_1: value_1, key_2:value2, key_3:value3}

Creating a Dictionary:

#creating empty dictionary


dictionary = {}
print(dictionary)

Output: { }

• To create a dictionary with one or more key-value pairs you can also use the dict
() function.
• The dict () creates a dictionary directly from a sequence of key value pairs.

# creating a dictionary using a list of key-value pairs

print(dict((('jersey','7'),('Name','Dhoni'),('Sport','Cricket'))))

Output

{'jersey': '7', 'Name': 'Dhoni', 'Sport': 'Cricket'}

Accessing Values:

• To access values from a dictionary square brackets are used along with the key to
obtain its value.

Source code

# Access values stored in a dictionary using a list of key-value pairs


dictionary = (dict((('jersey','7'),('Name','Dhoni'),('Sport','Cricket'))))

print("jersey:", dictionary["jersey"])
print("Name:", dictionary["Name"])
print("Sport:", dictionary["Sport"])
Output

jersey: 7
Name: Dhoni
Sport: Cricket

Source code

#if you try to access an item with a key which is not specified in the dictionary, a key
Error is generated

print("marks:=", dictionary["marks"])

Output

Traceback (most recent call last):


File "C:/Users/admin/.spyder-py3/grade.py", line 19, in <module>
print("marks:=", dictionary["marks"])
KeyError: 'marks'

Adding and modifying an item in a dictionary:

• To add a new entry or a key value pair in a dictionary you must specify the key-
value pair.

Syntax: dictionary [key] = Val

Source Code

dictionary = (dict((('jersey','7'),('Name','Dhoni'),('Sport','Cricket'))))

print("jersey:", dictionary["jersey"])
print("Name:", dictionary["Name"])
print("Sport:", dictionary["Sport"])

print("Marks is the new item added to a dictionary")


dictionary["Marks"] = 95
print("Marks:", dictionary["Marks"])

Output

jersey: 7
Name: Dhoni
Sport: Cricket
Marks is the new item added to a dictionary
Marks: 95

Deleting Items:

• We can delete one or more items using the del keyword.


• To delete or remove all the items in just one state we can use clear () function.

Syntax: del dictionary [key]

Example: dictionary.clear () # deletes all entries


Example: del dictionary #deletes the variable dictionary from the memory.

Programming examples of Dictionary.

• Program to illustrate the use of duplicates keys in a dictionary.


• Program to illustrate the use of mutable keys in a dictionary.
• Program to use tuple as keys.
• Program to check single key in a dictionary.

Sorting items in a dictionary:

• The keys() method of dictionary returns a list of all the keys used in the
dictionary in arbitrary order.
• The sorted () function is used to sort the keys.
Source Code

dictionary = (dict((('jersey','7'),('Name','Dhoni'),('Sport','Cricket'))))
print(sorted(dictionary.keys()))

Output

['Name', 'Sport', 'jersey']


Nested Dictionaries:

Source Code

#Program to illustrate nested dictionary (use of dictionary inside another)

students = {"Shivaraj" : {'CS':90, 'DS':70, 'DBMS':70},


"Shruthi" : {'STATS':90,'ACCOUNTS':80,'TAX':70},
"Kirthi" : {'ZOOLOGY':100,'BOTANY':100,'CHEMISTRY':100}}
for key, val in students.items():
print(key,val)

Output

Shivaraj {'CS': 90, 'DS': 70, 'DBMS': 70}


Shruthi {'STATS': 90, 'ACCOUNTS': 80, 'TAX': 70}
Kirthi {'ZOOLOGY': 100, 'BOTANY': 100, 'CHEMISTRY': 100}

Built-in Dictionary Functions and Methods:

Operation Description
len(dict) Returns the length of dictionary. That is number of items(key-
value pairs)
str(dict) Returns a string representation of the dictionary
dict.clear() Deletes all entries in the dictionary
dict.copy() Returns a shallow copy of the dictionary, i.e. the dictionary
returned will not have a duplicate copy of dict but will have the
same reference
dict.get(key) Returns the value for the key passed as argument.
dict.has_key() Returns True if the key is present in the dictionary and False
otherwise
dict.items() Returns a list of tuples
dict.keys() Returns a list of keys in the dictionary
dict1.update(dict2) Adds the key-value pairs of dict1 to the key-value of dict2
dict.values() Returns a list of values in dictionary
dict.iteritems() Used to iterate through items in the dictionary
In and not in Checks whether a given key is present in dictionary or not

String formatting with dictionaries:

Python allows string formatting with dictionaries with the help of %S, %D, %F to
represent sting, integer and float values.
Source Code

#Program that uses string formating feature to print the key-value pairs stored in the
dictionary

dictionary = {"Shivaraj" : "M.Tech", "Shruthi" : "M.Com"}


for key, val in dictionary.items():
print("%s got his %s" %(key,val))

Output

Shivaraj got his M.Tech


Shruthi got his M.Com

Programs:

Program 1

Write a program that has dictionary of names of students and a list of their marks in
four subjects. Create another dictionary from this dictionary that has name of the
student and their total marks. Find out topper and his/her score.

Source Code

Marks=
{"Shivaraj":[45,78,75,65],"Shruthi":[65,70,70,70],"Kirthi":[80,50,45,60],"Shwetha":[45
,55,60,70]}

total = 0

total_marks = Marks.copy()
for key,val in Marks.items():
total = sum(val)
total_marks[key] = total
print(total_marks)

max = 0
topper = ''
for key, val in total_marks.items():
if val>max:
max = val
topper = key
print("Topper is : ", topper, "with marks=",max)

Output

{'Shivaraj': 263, 'Shruthi': 275, 'Kirthi': 235, 'Shwetha': 230}


Topper is : Shruthi with marks= 275

Program 2

Write a program that generates a set of prime numbers and another set of odd numbers.
Demonstrate the result of union, intersection, difference and symmetric difference
operations on these sets.

Source Code

odds = set([x*2+1 for x in range(1,10)])

print(odds)
prime = set()
for i in range(2,20):
j=2
flag = 0
while j<i/2:
if i%j == 0:
flag = 1
j+=1
if flag == 0:
prime.add(i)

print(prime)
print("union:", odds.union(prime))
print("intersection:", odds.intersection(prime))
print("difference:", odds.difference(prime))
print("symmetric_difference:", odds.symmetric_difference(prime))

output

{3, 5, 7, 9, 11, 13, 15, 17, 19}


{2, 3, 4, 5, 7, 11, 13, 17, 19}
union: {2, 3, 4, 5, 7, 9, 11, 13, 15, 17, 19}
intersection: {3, 5, 7, 11, 13, 17, 19}
difference: {9, 15}
symmetric_difference: {2, 4, 9, 15}

Program 3

Write a program that creates a list of 10 random integers. Then create ODD list and
EVEN list that has all odd and even values in the list respectively?

Source Code

list1 = [11, 22, 33, 44, 55, 50, 19, 75, 60, 80]

# declare listOdd - to store odd numbers


# declare listEven - to store even numbers
listOdd = [ ]
listEven = [ ]

# check and append odd numbers in listOdd and even numbers in listEven

for num in list1:


if num%2 == 0:
listEven.append(num)
else:
listOdd.append(num)

# print lists
print ("list1: ", list1)
print ("listEven: ", listEven)
print ("listOdd: ", listOdd)

Output

list1: [11, 22, 33, 44, 55, 50, 19, 75, 60, 80]
listEven: [22, 44, 50, 60, 80]
listOdd: [11, 33, 55, 19, 75]
Program 4

Write a program to print index at which a particular value exists. If the value exits at
multiple locations in the list, then print all the indices. Also, count the number of times
that value is repeated in the list.

Source Code

num_list = [1,2,3,4,5,6,5,4,3,2,1]
num = int(input("Enter the values to be searched:"))
i=0
count = 0
while i<len(num_list):
if num == num_list[i]:
print(num,"found at location", i)
count+=1
i+=1
print(num,"appears", count, "times in the list")

Output

Enter the values to be searched:5


5 found at location 4
5 found at location 6
5 appears 2 times in the list

***************************************************************************************

Good Luck

You might also like