Unit 3
Unit 3
UNIT 3
Python Data Structure
Python Strings Lists and Tuples Sets Dictionaries 2/100
Unit 3 Outline I
1 Python Strings
3 Sets
4 Dictionaries
Python Strings Lists and Tuples Sets Dictionaries 3/100
1 Python Strings
3 Sets
4 Dictionaries
Python Strings Lists and Tuples Sets Dictionaries 4/100
Python Strings
The python string data type is a sequence made up of one or more
individual characters, where a character could be a letter, digit,
whitespace or any other symbol.
Python treats strings as contiguous series of characters delimited by
single, double or triple quotes.
Multi-line strings are specified using triple quotes.
1 >>> a = 'Hello'
2 >>> b = "Hello"
3 >>> c = '''Hello everyone.
4 ... "Welcome to the world of 'python'."
5 ... Happy learning.'''
6 >>> print(c)
7 Hello everyone.
8 "Welcome to the world of 'python'."
9 Happy learning.
Python has built in string class str that has many useful features.
Python Strings Lists and Tuples Sets Dictionaries 5/100
Python Strings
A string is a sequence of characters
Lowercase and uppercase characters have different encoding and
hence strings are case-sensitive
1 >>> a = 'a'
2 >>> b = 'abc'
3 >>> name = 'python'
4 >>> type(name)
5 <class str'>
6 >>> print(name)
7 python
Python Strings Lists and Tuples Sets Dictionaries 6/100
Python Strings
Escape sequences (\’,\”,\\, \n, \t etc.) are used to print certain
characters such as (’, ,”, \, newline, tab etc)
1 >>> s1 = "red"
2 >>> s2 = "apple"
3 >>> len(s1) # find length of string 's1'
4 3
5 # concatenate two strings and assign it to 's3'
6 >>> s3 = s1 + ' ' + s2
7 >>> print(s3)
8 red apple
9 >>> print("Hello " + str(1234))
10 Hello 1234
11 >>> print("Hello ", str(1234))
12 Hello 1234
Python Strings Lists and Tuples Sets Dictionaries 14/100
1 ch = 'R'
2 print(ord(ch))
3 print(chr(82 + 32))
4 print(ord('a'))
5 print(chr(ord('a') - 32))
6
7 OUTPUT
8 82
9 'r'
10 97
11 'A'
Python Strings Lists and Tuples Sets Dictionaries 18/100
Function Usage
Function Usage
OUTPUT OUTPUT
7 ValueError: substring not found
OUTPUT OUTPUT
FOllo FOllo FOllo The World Is Beautiful
Python Strings Lists and Tuples Sets Dictionaries 26/100
OUTPUT OUTPUT
tHE wORLD iS bEAUTIFUL ['abc', 'def', ' ghi', 'jkl']
OUTPUT OUTPUT
FOllo FOllo FOllo The World Is Beautiful
Python Strings Lists and Tuples Sets Dictionaries 27/100
1 Python Strings
3 Sets
4 Dictionaries
Python Strings Lists and Tuples Sets Dictionaries 28/100
Data Structure
Data structure is a group of data elements that are put together
under one name
Data structure defines a particular way of storing and organizing data
in a computer so that it can be used efficiently
Sequence is the most basic data structure in Python
In the sequence data structure, each element has a specific index
The index value starts from zero and it automatically incremented for
the next element in the sequence
Python Strings Lists and Tuples Sets Dictionaries 29/100
Lists
List is a sequence in which elements are written as a list of
comma-separated values (items) between square brackets
The key feature of a list is that it can have elements that belong to
different data types
The syntax for defining a list can be given as
List_variable = [val1, val2, ...]
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]
Python Strings Lists and Tuples Sets Dictionaries 31/100
OUTPUT
List is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List after updation is : [1, 2, 3, 4, 5, 100, 7, 8, 9, 10]
List after appending a value is [1, 2, 3, 4, 5, 100, 7, 8, 9, 10, 200]
List after deleting a value is [1, 2, 3, 5, 100, 7, 8, 9, 10, 200]
List after deleting a value is [1, 2, 100, 7, 8, 9, 10, 200]
Python Strings Lists and Tuples Sets Dictionaries 32/100
num_list = [1,9,11,13,15]
print("Original list : ", num_list)
num_list[2] = [3,5,7]
print("Updated list is : ", num_list)
print("num_list[2] : ", num_list[2])
print("num_list[2][1] : ", num_list[2][1])
OUTPUT
Original list : [1, 9, 11, 13, 15]
Updated list is : [1, 9, [3, 5, 7], 13, 15]
num_list[2] : [3, 5, 7]
num_list[2][1] : 5
Python Strings Lists and Tuples Sets Dictionaries 33/100
a = [1,2,3,4,5]
b = a # copies a list using reference
c = a[:] # copies a list using cloning
a[3] = 100
print("a = ", a)
print("b = ", b)
print("c = ", c)
OUTPUT
a = [1, 2, 3, 100, 5]
b = [1, 2, 3, 100, 5]
c = [1, 2, 3, 4, 5]
Python Strings Lists and Tuples Sets Dictionaries 34/100
List : Methods
List : Methods
a = [6,3,1,0,1,2,3,1] a = [6,3,7,0,1,2,4,9]
print(a.count(1)) a.append(10)
print(a)
OUTPUT
3 OUTPUT
[6,3,7,0,1,2,4,9,10]
a = [6,3,7,0,3,7,6,0] a = [6,3,7,0,3,7,6,0]
print(a.index(7)) a.insert(3,100)
print(a)
OUTPUT
2 OUTPUT
[6,3,7,100,0,3,7,6,0]
List : Methods
insert(), remove() and sort() methods only modify the list and do not
return any value
sort() method uses ASCII values to sort the values in the list which
means uppercase letter comes before lowercase letters and numbers
comes even before the uppercase letters
OUTPUT
[1, 2, 'B', 'Def', 'a', 'abc']
Python Strings Lists and Tuples Sets Dictionaries 38/100
List : Stack
Stack is a linear data structure in which elements are added and
removed from one end.
Stack is called a LIFO (Last-In-First-Out) data structure, as the
element that was inserted last is the first one to be taken out.
A stack supports three basic operations : push, pop and peep (or
peek).
The push operation adds an element at the end of the stack.
The pop operation removes the last element from the stack.
The peep operation returns the last value of the last element of the
stack (without deleting it).
Python Strings Lists and Tuples Sets Dictionaries 39/100
List : Stack
In python, the list methods make it very easy to use list as a stack.
To push an element in the stack, append() method, to pop an element
pop() method and for peep operation the slicing operation can be use
stack = [1,2,3,4,5,6]
print("Original stack is : ", stack)
stack.append(7)
print("Stack after push operation is : ", stack)
stack.pop()
print("Stack after 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 push operation is : [1, 2, 3, 4, 5, 6, 7]
Stack after pop operation is : [1, 2, 3, 4, 5, 6]
Value obtained after peep operation is : 6
Python Strings Lists and Tuples Sets Dictionaries 40/100
List : Queue
A queue is FIFO (First-In-First-Out) data structure in which the
element that is inserted first is the first one to be taken out
The element in a queue are added at one end and removed from the
other end
Queue supports three basic operations - insert, delete and peep
In python, queue can be implemented by using append() method to
insert an element at the end of the queue, pop() method with an
index 0 to delete the first element from the queue and slice operation
to print the value of the last element in the queue
Python Strings Lists and Tuples Sets Dictionaries 41/100
List : Queue
queue = [1,2,3,4,5,6]
print("Original queue is : ", queue)
stack.append(7)
print("Queue after insertion is : ", queue)
stack.pop(0)
print("Queue after deletion is : ", queue)
last_element_index = len(stack) - 1
print("Value obtained after peep operation is : ",
queue[len(queue) - 1])
OUTPUT
Original queue is : [1, 2, 3, 4, 5, 6]
Queue after insertion is : [1, 2, 3, 4, 5, 6, 7]
Stack after deletion is : [2, 3, 4, 5, 6, 7]
Value obtained after peep operation is : 7
Python Strings Lists and Tuples Sets Dictionaries 42/100
List Comprehensions
List comprehensions help programmers to create lists in a concise way.
This is mainly beneficial to make new lists where each element is
obtained by some operations to each member of another sequence or
iterable.
List comprehension is also used to create a subsequence of those
elements that satisfy certain conditions.
List comprehensions having the following syntax
List = [expression for variable in sequence if condition]
OUTPUT
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Python Strings Lists and Tuples Sets Dictionaries 43/100
List Comprehensions
print([(x,y) for x in [10,20,30] for y in [30,10,40] if x != y])
OUTPUT
[(10,30), (10,40), (20,30), (20,10), (20,40), (30,10), (30,40)]
OUTPUT
['apple', 'orange', 'cherry', 'kiwi', 'mango']
Lists : Looping
Python’s for and in constructs are extremely useful when working
with lists
OUTPUT
Sum of elements in the list = 55
Average of elements in the list = 5.5
Python Strings Lists and Tuples Sets Dictionaries 45/100
Lists : Looping
enumerate() function is useful when to print both index as well as
an item in the list
enumerate() function returns an enumerate object which contains
the index and value of all the items of the list as a tuple
num_list = [1,2,3,4,5]
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
Python Strings Lists and Tuples Sets Dictionaries 46/100
Lists : Looping
To print index, range() function can also be used
num_list = [1,2,3,4,5]
for i in range(len(num_list)):
print("index : ", i)
OUTPUT
index : 0
index : 1
index : 2
index : 3
index : 4
Python Strings Lists and Tuples Sets Dictionaries 47/100
Lists : Looping
The built-in iter() function creates an iterator which can be used to
loop over the element of the list
The iterator fetches the value and then automatically points to the
next element in the list when used with the next() method
num_list = [1,2,3,4,5]
it = iter(num_list)
for i in range(len(num_list)):
print("Element at index ", i, " is : ", next(it))
OUTPUT
Element at index 0 is : 1
Element at index 0 is : 2
Element at index 0 is : 3
Element at index 0 is : 4
Element at index 0 is : 5
Python Strings Lists and Tuples Sets Dictionaries 48/100
def check(x):
if (x % 2 == 0 or x % 4 == 0):
return 1
# call check() for every value between 2 to 21
evens = list(filter(check, range(2,22)))
print(evens)
OUTPUT
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Python Strings Lists and Tuples Sets Dictionaries 49/100
# WAP that has a list of both positive and negative numbers. Create
# another list using filter() that has only positive values
def is_positive(x):
if x > 0:
return x
num_list = [10, -20, 30, -40, 50, -60, 70, -80, 90, -100]
pos_list = list(filter(is_positive, num_list))
print("Positive value list = ", new_list)
OUTPUT
Positive value list = [10, 30, 50, 70, 90]
Python Strings Lists and Tuples Sets Dictionaries 50/100
def add_2(x):
x += 2
return x
num_list = [1, 2, 3, 4, 5, 6, 7]
print("Original list is : ", num_list)
new_list = list(map(add_2, num_list))
print("Modified list is : ", new_list)
OUTPUT
Original list is : [1, 2, 3, 4, 5, 6, 7]
Modified list is : [3, 4, 5, 6, 7, 8, 9]
Python Strings Lists and Tuples Sets Dictionaries 51/100
def add(x,y):
return x+y
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
list3 = list(map(add, list1, list2))
print("Sum of ", list1, " and ", list2, " = ", list3)
OUTPUT
Sum of [1, 2, 3, 4, 5] and [6, 7, 8, 9, 10] = [7, 9, 11, 13, 15]
Python Strings Lists and Tuples Sets Dictionaries 52/100
Lists: Example
WAP to print index at which a particular value exists in the list. If
the value exists at multiple locations in the list, then print all the
indices. Also, count the number of times that value is repeated in
the list.
Python Strings Lists and Tuples Sets Dictionaries 53/100
Lists: Example
WAP to print index at which a particular value exists in the list. If
the value exists at multiple locations in the list, then print all the
indices. Also, count the number of times that value is repeated in
the list.
num_list = [1,2,3,4,5,6,5,4,3,2,1]
num = int(input("Enter the value to be searched : "))
i = 0
count = 0
while i < len(num_list):
if num == num_list[i]:
print(num, " found at index ", i)
count += 1
i += 1
print(num, " appears ", count, " times in the list")
OUTPUT
Enter the value to be searched : 4
4 found at index 3
4 found at index 7
4 appears 2 times in the list
Python Strings Lists and Tuples Sets Dictionaries 54/100
Tuple
Tuple is another data structure in Python similar to lists but differ in
two things
- A tuple is a sequence of immutable objects which means that the
value cannot be changed in a tuple
- Tuple use parentheses to define its elements whereas lists uses square
brackets
Tuple can be created by different comma-separated values within a
parentheses
Tup = (val_1, val_2, ...)
Any set of multiple, comma-separated values written without an
brackets [] (for list) and parantheses () (for tuple) etc. are treated as
tuples by default
Python Strings Lists and Tuples Sets Dictionaries 55/100
Tuple
OUTPUT
(1,2,3)
(1, 2, 3, 4, 5)
('a', 'b', 'c', 'd')
('abc', 'def', 'ghi')
(1, 'abc', 2.3, 'd')
Python Strings Lists and Tuples Sets Dictionaries 56/100
Tuple : Assignment
OUTPUT
1 2 3
100 200 300
6 5.666667 3
Python Strings Lists and Tuples Sets Dictionaries 57/100
Tup = (1,2,3,4,5,6,7,8,9,10)
print("Tup[3:6] = ", Tup[3:6])
print("Tup[:4] = ", Tup[:4])
print("Tup[4:] = ", Tup[4:])
print("Tup[:] = ", Tup[:])
OUTPUT
Tup[3:6] = (4, 5, 6)
Tup[:4] = (1, 2, 3, 4)
Tup[4:] = (5, 6, 7, 8, 9, 10)
Tup[:] = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Python Strings Lists and Tuples Sets Dictionaries 58/100
Tup1 = (1,2,3,4,5)
Tup2 = (6,7,8,9,10)
Tup3 = Tup1 + Tup2
print(Tup3)
OUTPUT
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Python Strings Lists and Tuples Sets Dictionaries 59/100
Length len((1,2,3,4,5)) 5
Concatenation (1,2,3) + (4,5,6) (1,2,3,4,5,6)
Repetition ('Good..',)*3 ('Good..','Good..','Good..')
Membership 5 in (1,2,3,4,5) True
for i in (1,2,3,4,5):
Iteration 1 2 3 4 5
print(i,end= ' ')
Tup1 = (1,2,3,4,5)
Comparision Tup2 = (5,1,2,3,4) True
print(Tup1<Tup2)
Maximum max(1,0,3,8,2,9) 9
Minimum min(1,0,3,8,2,9) 0
tuple("Hello") ('H','e','l','l','o')
Convert to tuple
tuple([1,2,3,4,5]) (1,2,3,4,5)
Python Strings Lists and Tuples Sets Dictionaries 60/100
def max_min(vals):
x = max(vals)
y = min(vals)
return (x,y)
vals = (99, 98, 90, 97, 89, 86, 93, 82)
(max_marks, min_marks) = max_min(vals)
print("Highest Marks = ", max_marks)
print("Lowest Marks = ", min_marks)
OUTPUT
Highest Marks = 99
Lowest Marks = 82
Python Strings Lists and Tuples Sets Dictionaries 61/100
Nested Tuples
It is possible to define a tuple inside another tuple and this is called a
nested tuple
List can also be defined within tuple
OUTPUT
Name : Janvi
Class and Enrol Number : ('CSE', 123)
Highest score in 4 subjects : ([94,95,96,97])
Modified score in 4 subjects : [94,98,96,97]
Python Strings Lists and Tuples Sets Dictionaries 62/100
a = "abcdxxxxabcdxxxxabcdxxxx"
a = tuple(a)
print("x appears ", a.count('x'), " times in a")
b = (1,2,3,1,2,3,1,2,3,1,2,3)
print("1 appears ", b.count(1), " times in b")
OUTPUT
x appears 12 times in a
1 appears 4 times in b
Python Strings Lists and Tuples Sets Dictionaries 63/100
def double(T):
return ([i*2 for i in T])
tup = 1,2,3,4,5
print("Original Tuple : ", tup)
print("Double values : ", double(tup))
OUTPUT
Original Tuple : (1, 2, 3, 4, 5)
Double values : [2, 4, 6, 8, 10]
Python Strings Lists and Tuples Sets Dictionaries 64/100
def display(*arg):
print(args)
t = (1,2,3)
display(t,1,2)
OUTPUT
((1, 2, 3), 4, 5)
Python Strings Lists and Tuples Sets Dictionaries 65/100
Tup = (1,2,3,4,5)
List1 = ['a','b','c','d','e']
print(list(zip(Tup, List1)))
List2 = ['a','b','c']
print(list(zip(Tup, List2)))
for i, char in zip(Tup,List2):
print(i, char)
OUTPUT
[(1,'a'), (2,'b'), (3,'c'), (4,'d'), (5,'e')]
[(1,'a'), (2,'b'), (3,'c')]
1 a
2 b
3 c
Python Strings Lists and Tuples Sets Dictionaries 66/100
OUTPUT
0 A
1 B
2 C
3 D
4 E
5 F
6 G
Python Strings Lists and Tuples Sets Dictionaries 67/100
Tuples : Example
WAP that accepts different number of arguments and return sum of
only the positive values passed to it.
Python Strings Lists and Tuples Sets Dictionaries 69/100
Tuples : Example
WAP that accepts different number of arguments and return sum of
only the positive values passed to it.
def sum_pos(*args):
tot = 0
for i in args:
if i > 0:
tot += i
return tot
OUTPUT
sum_pos(1,-9,2,-8,3,-7,4,-6,5) = 15
Python Strings Lists and Tuples Sets Dictionaries 70/100
1 Python Strings
3 Sets
4 Dictionaries
Python Strings Lists and Tuples Sets Dictionaries 71/100
Sets
Sets is another data structure in Python which is similar to the lists
but with a difference that sets are lists with no duplicate entries
Set is a mutable and an unordered collection of items in which
items can be easily added or removed from it
A set is created by placing all the elements inside curly brackets,
separated by comma or by using the built-in function set().
The syntax of creating a set can be given as
set_variable = {val1, val2, ...}
s = {1,2.0,"abc"}
print(s)
a = set([1,2,'a','b','def', 4.56])
print(a)
OUTPUT
set([1, 2.0, 'abc'])
set(['a', 1, 2, 'b', 4.56, 'def'])
Python Strings Lists and Tuples Sets Dictionaries 72/100
Sets
If we add the same element multiple times in a set, they are removed
because a set cannot have duplicate values
List1 = [1,2,3,4,5,6,5,4,3,2,1]
print(set(list1)) # list is converted into a set
Tup1 = ('a','b','c','d','b','e','a')
print(set(Tup1)) # tuple is converted into a set
str = "abcdefabcdefg"
print(set(str)) # string is converted into a set
# forms a set of words
print(set("She sells sea shells on the sea shore".split()))
OUTPUT
set([1, 2, 3, 4, 5, 6])
set(['a', 'c', 'b', 'e', 'd'])
set(['a', 'c', 'b', 'e', 'd', 'g', 'f'])
set(['on', 'shells', 'shore', 'She', 'sea', 'sells', 'the'])
Python Strings Lists and Tuples Sets Dictionaries 73/100
Sets
Python Strings Lists and Tuples Sets Dictionaries 74/100
Sets
Coders = set(["Arnav","Goransh","Mani","Parul"])
Analysts = set(["Krish","Mehak","Shiv", "Goransh","Mani"])
print("Coders : ", Coders)
print("Analysts : ", Analysts)
print("People working as Coders as well as Analysts : ",
Coders.intersection(Analysts))
print("People working as Coders or Analysts : ",
Coders.union(Analysts))
print("People working as Coders but not Analysts : ",
Coders.difference(Analysts))
print("People working as Analysts but not Coders : ",
Analysts.difference(Coders))
print("People working in only one of the groups : ",
Coders.symmetric_difference(Analysts))
OUTPUT
Coders : {'Mani', 'Arnav', 'Goransh', 'Parul'}
Analysts : {'Goransh', 'Krish', 'Mehak', 'Mani', 'Shiv'}
People working as Coders as well as Analysts : {'Mani', 'Goransh'}
People working as Coders or Analysts : {'Arnav', 'Goransh', 'Krish',
'Mehak', 'Mani', 'Shiv', 'Parul'}
People working as Coders but not Analysts : {'Arnav', 'Parul'}
People working as Analysts but not Coders : {'Shiv', 'Krish', 'Mehak'}
People working in only one of the groups : {'Krish', 'Mehak',
'Shiv', 'Arnav', 'Parul'}
Python Strings Lists and Tuples Sets Dictionaries 75/100
Set Operations
Operation Description Code Output
s.update([1,2,3,4,5])
Adds elements of set s provided t = set([6,7,8])
s.update(t) {1,2,3,4,5,6,7,8}
that all duplicates are avoided s.update(t)
print(s)
Adds element x to the set s s = set([1,2,3,4,5])
s.add(x) provided that all duplicates are s.add(6) {1,2,3,4,5,6}
avoided print(s)
Removes element x from set s. s = set([1,2,3,4,5])
s.remove(x) Returns KeyError if x is not s.remove(3) {1,2,4,5}
present print(s)
Same as remove() but does not s = set([1,2,3,4,5])
s.discard(x) give error if x is not present in s.discard(3) {1,2,4,5}
the set print(s)
Removes and returns any s = set([1,2,3,4,5])
s.pop() arbitrary element from s. s.pop() {2,3,4,5}
KeyError is raised if s is empty. print(s)
s = set([1,2,3,4,5])
Removes all elements from the
s.clear() s.clear() set()
set
print(s)
Python Strings Lists and Tuples Sets Dictionaries 76/100
Set Operations
Operation Description Code Output
s.update([1,2,3,4,5])
len(s) Returns the length of set 5
print(len(s))
Returns True if every s = set([1,2,3,4,5])
s.issubset(t) element in s is present in set t = set([1,2,3,4,5,6,7]) True
t and False otherwise s<=t
Returns True if every s = set([1,2,3,4,5])
element in t is present in set
s.issuperset(t) t = set([1,2,3,4,5,6,7]) False
s and False otherwise s.issuperset(t)
Returns a set that has s = set([1,2,3,4,5])
s.union(t) elements from both sets s t = set([1,2,3,4,5,6,7]) {1,2,3,4,5,6,7}
and t s|t
Returns a new set that has s = set([1,2,3,4,5])
elements which are common
s.intersection(t) t = set([1,2,3,4,5,6,7]) {1,2,3,4,5}
to both the sets s and t s&t
s = set([1,2,10,12])
Returns a new set that has t = set([1,2,3,4,10])
s.difference(t) {12}
elements in set s but not in t z = s - t
print(z)
Python Strings Lists and Tuples Sets Dictionaries 77/100
Set Operations
Operation Description Code Output
s = set([1,2,10,12])
Returns a new set with
s.symmetric_ t = set([1,2,3,4,5,6])
elements either in s or in t {3,4,5,6,10,12}
difference(t) but not both z = s^t
print(z)
s = set([1,2,3,4,5])
s.copy() Returns a copy of set s t = s.copy() {1,2,3,4,5}
print(t)
Returns True if all elements s = set([0,1,2,3,4])
all(s) in the set are True and False print(all(s)) False
otherwise
Returns True if any of the s = set([0,1,2,3,4])
any(s) elements in the set s is True. print(any(s)) True
Returns False if the set is
empty.
s = set([5,4,3,2,1,0])
Return a new sorted list
sorted(s) print(sorted(s)) [0,1,2,3,4,5]
from elements in the set.
Python Strings Lists and Tuples Sets Dictionaries 78/100
Sets
Since sets are unordered, indexing have no meaning in set data types.
Set operations do not allow users to access or change an element
using indexing or slicing.
1 s = {1,2,3,4,5}
2 print(s[0])
3
4 OUTPUT
5 Traceback (most recent call last):
6 File "C:\Python34\Try.py", line 2, in <module>
7 print(s[0])
8 TypeError: 'set' object does not support indexing
A set can be created from a list but a set cannot contain a list.
Python Strings Lists and Tuples Sets Dictionaries 79/100
1 Python Strings
3 Sets
4 Dictionaries
Python Strings Lists and Tuples Sets Dictionaries 80/100
Dictionaries
Dictionary is a data structure in which values are stored 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 ({})
The syntax for defining dictionary is
If many keys and values in dictionaries, then one key-value pair can
be written per line for easy reading and understanding.
Dictionaries
Dictionary keys are case-sensitive
While keys in the dictionary must be unique and be of any immutable
data types (like strings, numbers or tuples), there is no stringent
requirement for uniqueness and type of values i.e. values can be of
any type
Dictionaries are not sequences, rather they are mappings
Mappings are collection of objects that store objects by key instead
of by relative position
Python Strings Lists and Tuples Sets Dictionaries 82/100
Creating a Dictionaries
Empty dictionary can be created as
Dict = {}
OUTPUT
{'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
OUTPUT
{'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
Python Strings Lists and Tuples Sets Dictionaries 83/100
Creating a Dictionaries
Dictionary comprehensions is another way of creating a dictionary.
A dictionary comprehension is a syntactic construct which creates a
dictionary based on existing dictionary
The syntax can be given as
OUTPUT
{1:2, 2:4, 3:6, 4:8, 5:10}
Python Strings Lists and Tuples Sets Dictionaries 84/100
dictionary_variable[key] = val
dict.pop(key [, default])
The pop() method removes an item from the dictionary and returns
its value and if the specified key is not present then default value is
returned.
Since default is optional, if default is not specified then KeyError is
generated.
Another method dict.popitem() randomly pops and returns an
item from the dictionary.
Python Strings Lists and Tuples Sets Dictionaries 89/100
OUTPUT
Name is : Arav
Dictionary after popping Name is : {'Course': 'BTech', 'Roll_No': '16/001'}
Marks is : -1
Dictionary after popping Marks is : {'Course': 'BTech', 'Roll_No': '16/001'}
Randomly popping any item : ('Course', 'BTech')
Dictionary after random popping is : {'Roll_No': '16/001'}
Python Strings Lists and Tuples Sets Dictionaries 90/100
Dictionary : Looping
It is possible to loop over a dictionary to access only values, only keys
and both using for loop.
Nested Dictionaries
print(Students['Shiv']['CS'])
print(Students['Sadhvi']['CSA'])
OUTPUT
Sadhvi {'CS':91, 'CSA':94, 'DS':87}
Krish {'CS':93, 'CSA':88, 'DS':92}
Shiv {'CS':90, 'CSA':92, 'DS':89}
90
94
Python Strings Lists and Tuples Sets Dictionaries 94/100
OUTPUT
3
Operation : str(Dict)
Description : Returns a string representation of the dictionary
Example :
OUTPUT
{'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
Python Strings Lists and Tuples Sets Dictionaries 95/100
OUTPUT
{}
Operation : Dict.iteritems()
Description : Used to iterate through items in the dictionary
Example :
Dict = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
for i,j in Dict.iteritems():
print(i,j)
OUTPUT
Course BTech
Name Arav
Roll_No 16/001
Python Strings Lists and Tuples Sets Dictionaries 96/100
OUTPUT
Dict2 : {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}
Dict1 after modification : {'Course': 'BTech', 'Name': 'Arav',
'Roll_No': '16/001'}
Dict2 after modification : {'Course': 'BTech', 'Name': 'Saesha',
'Roll_No': '16/001'}
Python Strings Lists and Tuples Sets Dictionaries 97/100
OUTPUT
{'OS':-1, 'DS':-1, 'CSA':-1, 'C++':-1}
Operation : Dict.get(key)
Description : Returns the value for the key passed as argument. If key is
not present in dictionary, it will return the default value. If no default
value is specified then it will return None
Dict1 = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
print(Dict1.get('Name'))
OUTPUT
Arav
Python Strings Lists and Tuples Sets Dictionaries 98/100
OUTPUT
[('Course', 'BTech'), ('Name', 'Arav'), ('Roll_No', '16/001')]
Operation : Dict.keys()
Description : Returns a list of keys in the dictionary
OUTPUT
['Course', 'Name', 'Roll_No']
Python Strings Lists and Tuples Sets Dictionaries 99/100
OUTPUT
['BTech', 'Arav', '16/001']
Operation : Dict1.update(Dict2)
Description : Adds the key-value pairs to Dict2 to the key-value pairs
of Dict1
Dict1 = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
Dict2 = {'Marks' : 90, 'Grade' : 'o'}
Dict1.update(Dict2)
print(Dict1)
OUTPUT
{'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech',
'Marks' : 90, 'Grade' : 'o'}
Python Strings Lists and Tuples Sets Dictionaries 100/100