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

Unit 3-1

Nice and useful pdf for everyone and pdf in language is very meaningful

Uploaded by

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

Unit 3-1

Nice and useful pdf for everyone and pdf in language is very meaningful

Uploaded by

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

Scripting Language – Python (4330701)

Unit 3 Lists, Tuples, Sets and Dictionaries


 There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate members.


 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
 Set is a collection which is unordered, unchangeable, and unindexed. No duplicate members.
 Dictionary is a collection which is ordered and changeable. No duplicate members.

 Lists and operations on Lists

List: It is used to store the sequence of various types of data.


Characteristics of List:
 List is ordered.
 It allows duplicate members.
 It is a general purpose, most widely used in data structures.
 It is mutable type(We can modify its element after it is created)
 Elements of list can access by index.
 Python lists are one of the most versatile data types that allow us to work with multiple elements at
once.
 To use a list, you must declare it first. It is declare using square brackets and separate values with
commas.

Create Python Lists


 In Python, a list is created by placing elements inside square brackets [], separated by commas.
Example:
x = [1, 2, 3]
print(x)
Output:
[1, 2, 3]
 A list can have any number of items and they may be of different types (integer, float, string, etc.).
Example:
x = []
x = [1, "Hello", 3.4]
print(x)
Output:
[1, 'Hello', 3.4]

List operations:
 These operations include indexing, slicing, adding, multiplying, and checking for
membership.
 We can also use + operator to combine two lists. This is also called concatenation.
 The * operator repeats a list for the given number of times.

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 1


Scripting Language – Python (4330701)

Access List Elements


 There are various ways in which we can access the elements of a list.

List Index
 We can use the index operator [ ] to access an item in a list. In Python, indices start at 0. So, a list
having 5 elements will have an index from 0 to 4.
x = ['h', 'e', 'l', 'l', 'o']

print(x[0]) # first character: h

print(x[2]) # third character: l

print(x[4]) # first character: o

# Nested List
x_list = ["Happy", [2, 0, 1, 3]]

print(x_list[0][1]) #a

print(x_list[1][3]) #3

Negative indexing
 Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the
second last item and so on.
x = ['h','e','l','l','o']

print(x[-1]) # last item :o

print(x[-5]) # fifth last item:h

List Slicing
 We can access a range of items in a list by using the slicing operator.
 We can get sublist of the list using syntax:
List(start:stop:step)
Where start –starting index of the list
Stop—last index of the list

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 2


Scripting Language – Python (4330701)
Step—skip the nth element within start and stop.
x=[2,4,6,8] x=[2,4,6,8]
print(x[:]) #Out put: [2, 4, 6, 8] print(x[-1]) #Out put:8
print(x[1:]) # Out put: [4, 6, 8] print(x[-3:]) #Out put: [4, 6, 8]
print(x[:2]) #Out put: [2, 4] print(x[:-2]) #Out put: [2, 4]
print(x[1:3]) #Out put: [4, 6] print(x[-3:-1]) #Out put: [4, 6]

x = ['h','e','l','l','0','w','o','r','l','d']

print(x[2:5]) # elements from index 2 to index 4 : ['l', 'l', '0']

print(x[5:]) # elements from index 5 to end: ['w', 'o', 'r', 'l', 'd']

print(x[:]) # elements beginning to end:['h', 'e', 'l', 'l', '0', 'w', 'o', 'r', 'l', 'd']

x=[10,20,30,40,50,60,70]
print(x[1:6:2]) #Out put: [20, 40, 60]

Add/Change List Elements


 Lists are mutable, meaning their elements can be changed unlike string or tuple.
 We can use the assignment operator = to change an item or a range of items.

x = [2, 4, 6, 8]

x[0] = 1 # change the 1st item : [1, 4, 6, 8]


print(x)

x[1:4] = [3, 5, 7] # change 2nd to 4th items : [1, 3, 5, 7]

print(x)

Append( ) and extend( ):


 We can add one item to a list using the append() method or add several items using the extend()
method.
x = [1, 3, 5]

x.append(7)
print(x) Output: [1, 3, 5, 7]

x.extend([9, 11, 13])


print(x) Output: [1, 3, 5, 7, 9, 11, 13]
Insert( )
 We can insert one item at a desired location by using the method insert() or insert multiple items by
squeezing it into an empty slice of a list.
x = [1, 9]
x.insert(1,3)

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 3


Scripting Language – Python (4330701)
print(x) Output: [1, 3, 9]

x[2:2] = [5, 7]

print(x) Output: [1, 3, 5, 7, 9]


Delete
 We can delete one or more items from a list using the Python del statement. It can even delete the list
entirely.
x = ['p', 'r', 'o', 'b', 'l', 'e', 'm']

del x[2] # delete one item

print(x) Output: ['p', 'r', 'b', 'l', 'e', 'm']

del x[1:5] # delete multiple items

print(x) Output: ['p', 'm']

del x # delete the entire list

print(x) # Error: List not defined


Remove( ) and pop( )
 We can use remove() to remove the given item or pop() to remove an item at the given index.
 The pop() method removes and returns the last item if the index is not provided
x = ['p','r','o','b','l','e','m']
x.remove('p')

print(x) # Output: ['r', 'o', 'b', 'l', 'e', 'm']

print(x.pop(1))

print(x) # Output: ['r', 'b', 'l', 'e', 'm']

print(x.pop())

print(x) # Output: ['r', 'b', 'l', 'e']

x.clear()

print(x) # Output: []
Iterating Through a List
 Using a for loop we can iterate through each item in a list.
for fruit in ['apple','banana','mango']:
print(fruit)
Output:
apple
banana
mango

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 4


Scripting Language – Python (4330701)

Reverse a List: The reverse () method reverses the elements of the list.
x = ['h', 'e', 'l', 'l', 'o'] Output:
x.reverse() ['o', 'l', 'l', 'e', 'h']
print(x)

Sort List: The sort() method sorts the items of a list in ascending or descending order.
x = ['w', 'o', 'r', 'l', 'd'] x=[10,2,56,3] x=[10,2,56,3]
x.sort() x.sort() x.sort(reverse=True)
print(x) print(x) print(x)

Output: ['d', 'l', 'o', 'r', 'w'] Output: [2, 3, 10, 56] Output: [56, 10, 3, 2]

Python List Built in Function:


Function Description Example
len(list) It is used to calculate the length of the list. x=[10,20,30,40,50,60,70]
print(len(x)) #Output:7
max(list) It returns the maximum element of the list x=[10,20,30,40,50,60,70]
print(max(x)) #Output:70
min(list) It returns the maximum element of the list x=[10,20,30,40,50,60,70]
print(min(x)) #Output: 10
list(seq) It converts any sequence to the list. str="abcd"
print(type(str)) # <class 'str'>
s=list(str)
print(type(s)) # <class 'list'>

 Tuples and operations on Tuples


Tuple: A tuple in Python is similar to a list.
 The difference between the two is that we cannot change the elements of a tuple once it is
assigned whereas we can change the elements of a list.

Characteristics of Tuple:
 It is ordered.
 It allows duplicate members.
 It is immutable type(We cannot modify its element after it is created)
 Elements of Tuple can access by index.
 To use a tuple, you must declare it first. It is declare using ( ) brackets and separate values with
commas.
 A tuple can also be created without using parentheses. This is known as tuple packing

Creating a Tuple: We can construct tuple in many ways:

X=() #no item tuple


X=(1,2,3)
X=tuple(list1)
X=1,2,3,4

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 5


Scripting Language – Python (4330701)

Example:
Example 1: Example 2:
>>> x=(1,2,3) >>> x=()
>>> print(x) >>> x
Output: (1, 2, 3) Output: ()
>>> x
Output: (1, 2, 3)

Example 3: Example 4:
>>> x=[4,5,66,9] >>> x=1,2,3,4
>>> y=tuple(x) >>> x
>>> y Output: (1, 2, 3, 4)
Output: (4, 5, 66, 9)
Example 5: # tuple with mixed Example 6: nested tuple
datatypes >>>x=("hello",[1,2,3],(4,5,6))
>>>x=(1,"hello",3.14) >>>x
>>>print(x) Output: ('hello', [1, 2, 3], (4, 5, 6))
Output: (1, 'hello', 3.14)
 A tuple can also be created without using parentheses. This is known as tuple packing.
x = 1,3.14,"hello"
print(x) # (1,3.14,’hello’)
a, b, c = x # tuple unpacking
print(a) #1
print(b) #3.14
print(c) # hello

Operations on Tuples
 Access tuple items(indexing, negative indexing and Slicing)
 Change tuple items
 Loop through a tuple
 Count()
 Length()

Access tuple items(Indexing):


 We can use the index operator [] to access an item in a tuple, where the index starts from 0.
 So, a tuple having 6 elements will have indices from 0 to 5.
Example: Example:
>>> x=('a','m','i') x = ('Hello', [8, 4, 6], (1, 2, 3)) # nested tuple
>>> print(x[2]) print(x[0][3]) # nested index : l
print(x[1][1]) # nested index : 4
Output: i
Output:
l
4

Negative Indexing: Python allows negative indexing for its sequences. The index of -1 refers to the
last item, -2 to the second last item and so on.

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 6


Scripting Language – Python (4330701)

x = ('h', 'e', 'l', 'l', 'o')


print(x[-1])
print(x[-5])
print(x[-6])
Output:
o
h
Traceback (most recent call last):
File "<string>", line 5, in <module>
IndexError: tuple index out of range
>

Slicing
We can access a range of items in a tuple by using the slicing operator colon :
x=(2,4,6,8) x=(2,4,6,8)
print(x[:]) #Out put: (2, 4, 6, 8) print(x[-1]) #Out put:8
print(x[1:]) # Out put: (4, 6, 8) print(x[-3:]) #Out put: (4, 6, 8)
print(x[:2]) #Out put: (2, 4) print(x[:-2]) #Out put: (2, 4)
print(x[1:3]) #Out put: (4, 6) print(x[-3:-1]) #Out put: (4, 6)

x = ('h','e','l','l','o','w','o','r','l','d')

print(x[1:4])
print(x[:-7])
print(x[7:])
print(x[:])

Output:
('e', 'l', 'l')
('h', 'e', 'l')
('r', 'l', 'd')
('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd')

Change tuple items: Once a tuple is created, you cannot change its values. Tuples are unchangeable.
>>> x=(2,5,7,'4',8)
>>> x[1]=10
Output:
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module> x[1]=10
Example:
x = (4, 2, 3, [6, 5])
x[3][0] = 9
print(x)

x = ('h', 'e', 'l', 'l', 'o')


print(x)

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 7


Scripting Language – Python (4330701)

Output:
(4, 2, 3, [9, 5])
('h', 'e', 'l', 'l', 'o')

Loop through a tuple(Iteration): We can loop the values of tuple using for loop
>>> x=4,5,6,7,2,'aa'
>>> for i in x:
print(i)
Output:
4
5
6
7
2
aa

Length (): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
Output: 12

Concatenation: We can use + operator to combine two tuples. This is called concatenation.
 We can also repeat the elements in a tuple for a given number of times using the * operator.
 Both + and * operations result in a new tuple.

Example:
print((1, 2, 3) + (4, 5, 6))
print(("Repeat",) * 3)

Output:
(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')

Deleting a Tuple: we cannot change the elements in a tuple. It means that we cannot delete or remove
items from a tuple.

Example:
x = (1,2,3)
del x
print(x)
Output:
Traceback (most recent call last):
File "<string>", line 8, in <module>
NameError: name 'x' is not defined

Tuple Methods

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 8


Scripting Language – Python (4330701)
x = ('h', 'e', 'l', 'l', 'o',)
print(x.count('l'))
print(x.index('e'))

Output:
2
1

Python List Built in Function:


Function Description Example
len(tuple) It is used to calculate the length of the tuple.
x=(10,20,30,40,50,60,70])
print(len(x)) #Output:7
max(tuple) It returns the maximum element of the tuple x=(10,20,30,40,50,60,70)
print(max(x)) #Output:70
min(tuple) It returns the maximum element of the tuple x=(10,20,30,40,50,60,70)
print(min(x)) #Output: 10
tuple (seq) It converts any sequence to the tuple. str="abcd"
print(type(str)) # <class 'str'>
s=tuple(str)
print(type(s)) # <class ‘tuple’>

 Where to use tuple?


 Tuple data is constant and must not be changed so when there is a requirement of read only data
tuple is preferable.
 Tuple can simulate a dictionary without key. For example:
[(10,”abc”,22), (20,”def”,34), (30,”xyz”,56)]

 Difference between List and Tuple


List Tuple
It is created by [ ] It is created by ( )
It is mutable It is immutable
It has variable length. It has fixed length.
It provides more functionality than a tuple. It provides less functionality than a list.
It is used where the values of items can be It is used where we need to store the read only
changed. collections.
It is less memory efficient than a tuple. It is more memory efficient than a list.
Example: a=[10,11,12] Example: a=(10,11,12)

 Sets and operations on Sets


 A set is an unordered collection of items. Every set element is unique (no duplicates) and must be
immutable (cannot be changed).
 Sets can also be used to perform mathematical set operations like union, intersection, symmetric
difference, etc.
 We cannot access or change an element of a set using indexing or slicing. Set data type does not
support it.
Characteristics of Set:
 Sets are unordered.

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 9


Scripting Language – Python (4330701)
 Set element is unique. Duplicate elements are not allowed.
 Set are immutable.(Can not change value)
 There is no index in set. So they donot support indexing or slicing operator.
 The set are used for mathematical operation like union,intersection,difference etc.

Creating Python Sets


 A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or by
using the built-in set() function.
 It can have any number of items and they may be of different types (integer, float, tuple, string etc.).
 To make a set without any elements, we use the set() function without any argument.

Example:
Example 1: Example 2:
x = {1, 2, 3} # set of mixed datatypes
print(x) x = {1.0, "Hello", (1, 2, 3)}
print(x)
Output:
{1, 2, 3} Output:
{1.0, (1, 2, 3), 'Hello'}
Example 3: Example 4:
# set cannot have duplicates x = set([1, 2, 3, 2])
x = {1, 2, 3, 4, 3, 2} print(x)
print(x)

Output: Output:
{1, 2, 3, 4} {1, 2, 3}
Example 5:

x= set()
print(type(x))

Output:
<class 'set'>

Access value in a Set: We cannot access individual values in a set. We can only access all the elements
together.
x = {1, 2, 3, 4, 3, 2}
for i in x:
print(I,end=’ ‘)

Output: 1 2 3 4

Modifying a set in Python


 We can add a single element using the add() method, and multiple elements using the update()
method. The update() method can take tuples, lists, strings or other sets as its argument. In all cases,
duplicates are avoided.

x = {1, 3} Output:

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 10


Scripting Language – Python (4330701)
print(x) {1, 3}

x.add(2) {1, 2, 3}
print(x)

x.update([2, 3, 4]) {1, 2, 3, 4}


print(x)
{1, 2, 3, 4, 5, 6, 8}
x.update([4, 5], {1, 6, 8})
print(x)

Removing elements from a set


 A particular item can be removed from a set using the methods discard() and remove().

 The only difference between the two is that the discard() function leaves a set unchanged if the
element is not present in the set. On the other hand, the remove() function will raise an error in such
a condition (if element is not present in the set).
x = {1, 3, 4, 5, 6} Output:
print(x) {1, 3, 4, 5, 6}
x.discard(4) {1, 3, 5, 6}
print(x)
{1, 3, 5}
x.remove(6)
print(x)

x.discard(2) {1, 3, 5}
print(x)
Traceback (most recent call last):
x.remove(2) File "<string>", line 28, in <module>
KeyError: 2

 Similarly, we can remove and return an item using the pop() method.
 Since set is an unordered data type, there is no way of determining which item will be popped.
 We can also remove all the items from a set using the clear() method.

x = set("abcdefgh") Output:
print(x) {'d', 'c', 'b', 'a', 'f', 'h', 'e', 'g'}

print(x.pop()) d

print(x.pop()) c

print(x) {'b', 'a', 'f', 'h', 'e', 'g'}


x.clear() set()
print(x)
Python Set Operations

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 11


Scripting Language – Python (4330701)
 Sets can be used to carry out mathematical set operations like union, intersection, difference and
symmetric difference. We can do this with operators or methods.

Set Union: Union of A and B is a set of all elements from both sets.Union is performed using | operator.
Same can be accomplished using the union() method.
A = {1, 2, 3, 4, 5} A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8} B = {4, 5, 6, 7, 8}
print(A | B) print(A.union(B))
print(B.union(A))

Output: Output:
{1, 2, 3, 4, 5, 6, 7, 8} {1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}

Set Intersection: Intersection of A and B is a set of elements that are common in both the sets.
Intersection is performed using & operator. Same can be accomplished using the intersection() method.
A = {1, 2, 3, 4, 5} A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8} B = {4, 5, 6, 7, 8}
print(A & B) print(A.intersection(B))
print(B.intersection(A))

Output:
Output: {4, 5} {4, 5}
{4, 5}
Set Difference: Difference of the set B from set A(A - B) is a set of elements that are only in A but not
in B. Similarly, B - A is a set of elements in B but not in A. Difference is performed using - operator.
Same can be accomplished using the difference() method.
A = {1, 2, 3, 4, 5} A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8} B = {4, 5, 6, 7, 8}
print(A - B) print(A.difference(B))
print(B. difference (A))

Output: {1,2,3} Output:


{1,2,3}
{6,7,8}
Set Symmetric Difference: Symmetric Difference of A and B is a set of elements in A and B but not in
both (excluding the intersection).Symmetric difference is performed using ^ operator. Same can be
accomplished using the method symmetric_difference().
A = {1, 2, 3, 4, 5} A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8} B = {4, 5, 6, 7, 8}
print(A ^ B) print(A.symmetric_difference(B))
print(B.symmetric_difference(A))
Output:{1,2,3,6,7,8}
Output: {1,2,3,6,7,8}
{1,2,3,6,7,8}
Set Membership Test: We can test if an item exists in a set or not, using the in keyword.
x = set("apple") Output:
True

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 12


Scripting Language – Python (4330701)
print('a' in x) False

print('p' not in x)

Iterating Through a Set: We can iterate through each item in a set using a for loop.
Example:
for letter in set("apple"): Output:
print(letter) a
p
l
e
Built-in Functions with Set

A = {1, 5, 3, 2, 4} Output:
print(len(A)) 5
print(min(A)) 1
print(max(A)) 5
print(sorted(A)) [1, 2, 3, 4, 5]
print(sum(A)) 15

 Dictionaries and operations on Dictionaries


 Python dictionary is an ordered collection of items. Each item of a dictionary has a key/value pair.
Characteristics of Dictionary:
 It is used to store data in a key-value pair format.
 It is mutable(changeable).
 Duplicate values are not allowed.
 Key must be a single element.
 Value can be of any type such as list,tuple,integer etc.

Creating Python Dictionary: Creating a dictionary is as simple as placing items inside curly braces {}
separated by commas.
An item has a key and a corresponding value that is expressed as a pair (key: value). We can also create a
dictionary using the built-in dict() function.

x = {} Output
print(x) {}

x = {1: 'Khush', 2: 'Milan'} # dictionary with integer keys


print(x) {1: 'Khush', 2: 'Milan'}

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 13


Scripting Language – Python (4330701)

x = {'name': 'Khush', 1: 'def'} {'name': 'Khush', 1: 'def'}


print(x)

x = dict({1:'khush', 2:'milan’}) # using dict() {1: ‘khush’, 2: 'milan'}


print(x)

x = dict([(1,'khush'), (2,'milan')]) {1: 'khush', 2: 'milan'}


print(x)
Accessing Elements from Dictionary:
 While indexing is used with other data types to access values, a dictionary uses keys.
 Keys can be used either inside square brackets [] or with the get() method.
x = {'name': 'Dharmesh', 'rollno': 1} Output

print(x['name']) Dharmesh
print(x.get('rollno')) 1
print(x.get('address')) # Output None None

print(x['address']) # Trying to access keys which doesn't exist throws error Traceback (most recent
call last):
File "<string>", line 9,
in <module>
KeyError: 'address'

Changing and Adding Dictionary elements:


 We can add new items or change the value of existing items using an assignment operator.
 If the key is already present, then the existing value gets updated. In case the key is not present, a new
(key: value) pair is added to the dictionary.

x = {'name': 'abc', 'rollno': 1} Output


print(x) {'name': 'abc', 'rollno': 1}

x['rollno'] = 20 # update value {'name': 'abc', 'rollno': 20}


print(x)

x['address'] = 'xyz' # adding value {'name': 'abc', 'rollno': 20, 'address': 'xyz'}
print(x)
Removing elements from Dictionary:
 We can remove a particular item in a dictionary by using the pop() method. This method removes an
item with the provided key and returns the value.
 The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the
dictionary.
 All the items can be removed at once, using the clear() method.
 We can also use the del keyword to remove individual items or the entire dictionary itself.

Using pop( ) Output:


squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} 16
print(squares.pop(4)) # remove a particular item, returns its value {1: 1, 2: 4, 3: 9, 5: 25}

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 14


Scripting Language – Python (4330701)
print(squares)
Using popitem( ) Output:
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares.popitem()) # remove an arbitrary item, return (key,value) (5, 25)
print(squares) {1: 1, 2: 4, 3: 9, 4: 16}
Using clear( ) Output:
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
squares.clear()
print(squares) {}
Using del keyword Output:
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
del squares[2]
print(squares) {1: 1, 3: 9, 4: 16, 5: 25}

del squares
print(squares) NameError: name
'squares' is not defined

Iterating Dictionary: A dictionary can be iterated using for loop.


Print only Key Output:
Student = {'Rollno': 1, 'Age':20, 'Marks':50}
for i in Student: Rollno Age Marks
print(i,end=" ")
Print only Values Output:
Student = {'Rollno': 1, 'Age':20, 'Marks':50}
for i in Student: 1 20 50
print(Student[i],end=" ")
Print Values using values( ) Output:
Student = {'Rollno': 1, 'Age':20, 'Marks':50}
for i in Student.values(): 1 20 50
print(i,end=" ")
Print Values using items( ) Output:
Student = {'Rollno': 1, 'Age':20, 'Marks':50}
for i in Student.items():
print(i,end=" ") ('Rollno', 1) ('Age', 20) ('Marks', 50)

Python Dictionary Comprehension:


 Dictionary comprehension is away to create a new dictionary from an iterable in Python.
 Dictionary comprehension consists of an expression pair (key: value) followed by a for statement
inside curly braces {}.
squares = {x: x*x for x in range(6)} Output:
print(squares) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
odd_squares = {x: x*x for x in range(11) if x % 2 == 1} Output:
print(odd_squares) {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 15

You might also like