0% found this document useful (0 votes)
5 views24 pages

Unit3 DataStructures

The document provides an overview of data structures in Python, focusing on lists, tuples, sets, and dictionaries. It covers various operations such as creation, indexing, slicing, and methods associated with lists, including appending, inserting, and removing elements. Additionally, it introduces list comprehensions and compares lists with tuples, emphasizing the immutability of tuples.

Uploaded by

Ananya Tiwari
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)
5 views24 pages

Unit3 DataStructures

The document provides an overview of data structures in Python, focusing on lists, tuples, sets, and dictionaries. It covers various operations such as creation, indexing, slicing, and methods associated with lists, including appending, inserting, and removing elements. Additionally, it introduces list comprehensions and compares lists with tuples, emphasizing the immutability of tuples.

Uploaded by

Ananya Tiwari
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/ 24

3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

UNIT – III - Data Structures:


Lists- Operations, Slicing, Methods, Tuples, Sets, Dictionaries, Se
quences, Comprehensions.

Data Structure:
A data structure is a collection of data elements (such as numbers or characters—or even other
data structures) that is structured in some way, for example, by numbering the elements. The most
basic data structure in Python is the "sequence".

Lists
-> List is one of the Sequence Data structure

-> Lists are collection of items (Strings, integers or even other lists)

-> Lists are enclosed in [ ]

-> Each item in the list has an assigned index value.

-> Each item in a list is separated by a comma

-> Lists are mutable, which means they can be changed.

List Creation
In [1]: emptyList = []

lst = ['one', 'two', 'three', 'four'] # list of strings

lst2 = [1, 2, 3, 4] #list of integers

lst3 = [[1, 2], [3, 4]] # list of lists

lst4 = [1, 'ramu', 24, 1.24] # list of different datatypes

print(lst4)

[1, 'ramu', 24, 1.24]

List Length

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 1/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [2]: lst = ['one', 'two', 'three', 'four']

#find length of a list


print(len(lst))

List Append
In [3]: lst = ['one', 'two', 'three', 'four']

lst.append('five') # append will add the item at the end

print(lst)

['one', 'two', 'three', 'four', 'five']

List Insert
In [4]: #syntax: lst.insert(x, y)

lst = ['one', 'two', 'four']

lst.insert(2, "three") # will add element y at location x

print(lst)

['one', 'two', 'three', 'four']

List Remove
In [5]: #syntax: lst.remove(x)

lst = ['one', 'two', 'three', 'four', 'two']

lst.remove('two') #it will remove first occurence of 'two' in a given list

print(lst)

['one', 'three', 'four', 'two']

List Append & Extend

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 2/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [6]: lst = ['one', 'two', 'three', 'four']

lst2 = ['five', 'six']

#append
lst.append(lst2)

print(lst)

['one', 'two', 'three', 'four', ['five', 'six']]

In [7]: lst = ['one', 'two', 'three', 'four']

lst2 = ['five', 'six']

#extend will join the list with list1

lst.extend(lst2)

print(lst)

['one', 'two', 'three', 'four', 'five', 'six']

List Delete
In [8]: #del to remove item based on index position

lst = ['one', 'two', 'three', 'four', 'five']

del lst[1]
print(lst)

#or we can use pop() method


a = lst.pop(1)
print(a)

print(lst)

['one', 'three', 'four', 'five']


three
['one', 'four', 'five']

In [9]: lst = ['one', 'two', 'three', 'four']

#remove an item from list


lst.remove('three')

print(lst)

['one', 'two', 'four']

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 3/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

List related keywords in Python


In [10]: #keyword 'in' is used to test if an item is in a list
lst = ['one', 'two', 'three', 'four']

if 'two' in lst:
print('AI')

#keyword 'not' can combined with 'in'


if 'six' not in lst:
print('ML')

AI
ML

List Reverse
In [11]: #reverse is reverses the entire list

lst = ['one', 'two', 'three', 'four']

lst.reverse()

print(lst)

['four', 'three', 'two', 'one']

List Sorting
The easiest way to sort a List is with the sorted(list) function.

That takes a list and returns a new list with those elements in sorted order.

The original list is not changed.

The sorted() optional argument reverse=True, e.g. sorted(list, reverse=True), makes it sort
backwards.

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 4/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [12]: #create a list with numbers


numbers = [3, 1, 6, 2, 8]

sorted_lst = sorted(numbers)

print("Sorted list :", sorted_lst)

#original list remain unchanged


print("Original list: ", numbers)

Sorted list : [1, 2, 3, 6, 8]


Original list: [3, 1, 6, 2, 8]

In [13]: #print a list in reverse sorted order


print("Reverse sorted list :", sorted(numbers, reverse=True))

#orginal list remain unchanged


print("Original list :", numbers)

Reverse sorted list : [8, 6, 3, 2, 1]


Original list : [3, 1, 6, 2, 8]

In [14]: lst = [1, 20, 5, 5, 4.2]

#sort the list and stored in itself


lst.sort()

# add element 'a' to the list to show an error

print("Sorted list: ", lst)

Sorted list: [1, 4.2, 5, 5, 20]

In [15]: lst = [1, 20, 'b', 5, 'a']


print(lst.sort()) # can't sort list with element of different datatypes.

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-15-f7fe17ce83fb> in <module>
1 lst = [1, 20, 'b', 5, 'a']
----> 2 print(lst.sort()) # can't sort list with element of different datatype
s.

TypeError: '<' not supported between instances of 'str' and 'int'

List Having Multiple References

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 5/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [22]: lst = [1, 2, 3, 4, 5]


abc = lst
abc.append(6)

#print original list


print("Original list: ", lst)

Original list: [1, 2, 3, 4, 5, 6]

String Split to create a list


In [23]: #let's take a string

s = "one,two,three,four,five"
slst = s.split(',')
print(slst)

['one', 'two', 'three', 'four', 'five']

In [24]: s = "This is applied AI Course"


split_lst = s.split() # default split is white-character: space or tab
print(split_lst)

['This', 'is', 'applied', 'AI', 'Course']

List Indexing
Each item in the list has an assigned index value starting from 0.

Accessing elements in a list is called indexing.

In [25]: lst = [1, 2, 3, 4]


print(lst[1]) #print second element

#print last element using negative index


print(lst[-2])

2
3

List Slicing
Accessing parts of segments is called slicing.

The key point to remember is that the :end value represents the first value that is not in the
selected slice.

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 6/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [26]: numbers = [10, 20, 30, 40, 50,60,70,80]

#print all numbers


print(numbers[:])

#print from index 0 to index 3


print(numbers[0:4])

[10, 20, 30, 40, 50, 60, 70, 80]


[10, 20, 30, 40]

In [27]: print (numbers)


#print alternate elements in a list
print(numbers[::2])

#print elemnts start from 0 through rest of the list


print(numbers[2::2])

[10, 20, 30, 40, 50, 60, 70, 80]


[10, 30, 50, 70]
[30, 50, 70]

List extend using "+"


In [28]: lst1 = [1, 2, 3, 4]
lst2 = ['varma', 'naveen', 'murali', 'brahma']
new_lst = lst1 + lst2

print(new_lst)

[1, 2, 3, 4, 'varma', 'naveen', 'murali', 'brahma']

List Count
In [29]: numbers = [1, 2, 3, 1, 3, 4, 2, 5]

#frequency of 1 in a list
print(numbers.count(1))

#frequency of 3 in a list
print(numbers.count(3))

2
2

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 7/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

List Looping
In [30]: #loop through a list

lst = ['one', 'two', 'three', 'four']

for ele in lst:


print(ele)

one
two
three
four

List Comprehensions
List comprehensions provide a concise way to create lists.

Common applications are to make new lists where each element is the result of some operations
applied to each member of another sequence or iterable, or to create a subsequence of those
elements that satisfy a certain condition.

In [31]: # without list comprehension


squares = []
for i in range(10):
squares.append(i**2) #list append
print(squares)

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In [32]: #using list comprehension


squares = [i**2 for i in range(10)]
print(squares)

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 8/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [33]: #example

lst = [-10, -20, 10, 20, 50]

#create a new list with values doubled


new_lst = [i*2 for i in lst]
print(new_lst)

#filter the list to exclude negative numbers


new_lst = [i for i in lst if i >= 0]
print(new_lst)

#create a list of tuples like (number, square_of_number)


new_lst = [(i, i**2) for i in range(10)]
print(new_lst)

[-20, -40, 20, 40, 100]


[10, 20, 50]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64),
(9, 81)]

Nested List Comprehensions


In [34]: #let's suppose we have a matrix

matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]

#transpose of a matrix without list comprehension


transposed = []
for i in range(4):
lst = []
for row in matrix:
lst.append(row[i])
transposed.append(lst)

print(transposed)

[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

In [35]: #with list comprehension


transposed = [[row[i] for row in matrix] for i in range(4)]
print(transposed)

[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

Tuples
localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 9/24
3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

-> A tuple is similar to list

-> The diffence between the two is that we can't change the elements of tuple once it is assigned
whereas in the list, elements can be changed

Tuple creation
In [36]: #empty tuple
t = ()

#tuple having integers


t = (1, 2, 3)
print(t)

#tuple with mixed datatypes


t = (1, 'xyz', 28, 'abc')
print(t)

#nested tuple
t = (1, (2, 3, 4), [1, 'xyz', 28, 'abc'])
print(t)

(1, 2, 3)
(1, 'xyz', 28, 'abc')
(1, (2, 3, 4), [1, 'xyz', 28, 'abc'])

In [37]: #only parenthesis is not enough


t = ('text')
type(t)

Out[37]: str

In [38]: #need a comma at the end


t = ('text',)
type(t)

Out[38]: tuple

In [39]: #parenthesis is optional


t = "text",
print(type(t))

print(t)

<class 'tuple'>
('text',)

Accessing Elements in Tuple

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 10/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [40]: t = ('ab', 'cd', 'ef', 'gh', 'xyz')

print(t[1])

cd

In [41]: #negative index


print(t[-1]) #print last element in a tuple

xyz

In [44]: #nested tuple


t = ('ABC', ('a', 'b', 'c'))

print(t[1])

('a', 'b', 'c')

In [45]: print(t[1][2])

In [46]: #Slicing
t = (1, 2, 3, 4, 5, 6)

print(t[1:4])

#print elements from starting to 2nd last elements


print(t[:-2])

#print elements from starting to end


print(t[:])

(2, 3, 4)
(1, 2, 3, 4)
(1, 2, 3, 4, 5, 6)

Changing a Tuple
-> unlike lists, tuples are immutable

This means that elements of a tuple cannot be changed once it has b


een assigned. But, if the element is itself a mutable datatype like lis
t, its nested items can be changed.

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 11/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [47]: #creating tuple


t = (1, 2, 3, 4, [5, 6, 7])

t[2] = 'x' #will get TypeError

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-47-1fb87c1270c4> in <module>
2 t = (1, 2, 3, 4, [5, 6, 7])
3
----> 4 t[2] = 'x' #will get TypeError

TypeError: 'tuple' object does not support item assignment

In [48]: t[4][1] = 'python'


print(t)

(1, 2, 3, 4, [5, 'python', 7])

In [49]: #concatinating tuples

t = (1, 2, 3) + (4, 5, 6)
print(t)

(1, 2, 3, 4, 5, 6)

In [50]: #repeat the elements in a tuple for a given number of times using the * operator.
t = (('hi', ) * 4)
print(t)

('hi', 'hi', 'hi', 'hi')

Tuple Deletion
In [51]: #we cannot change the elements in a tuple.
# That also means we cannot delete or remove items from a tuple.

#delete entire tuple using del keyword


t = (1, 2, 3, 4, 5, 6)

#delete entire tuple


del t

Tuple Count

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 12/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [52]: t = (1, 2, 3, 1, 3, 3, 4, 1)

#get the frequency of particular element appears in a tuple


t.count(1)

Out[52]: 3

Tuple Index
In [53]: t = (1, 2, 3, 1, 3, 3, 4, 1)

print(t.index(3)) #return index of the first element is equal to 3

#print index of the 1

Tuple Memebership
In [54]: #test if an item exists in a tuple or not, using the keyword in.
t = (1, 2, 3, 4, 5, 6)

print(1 in t)

True

In [55]: print(7 in t)

False

Built in Functions

Tuple Length
In [56]: t = (1, 2, 3, 4, 5, 6)
print(len(t))

Tuple Sort

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 13/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [57]: t = (4, 5, 1, 2, 3)

new_t = sorted(t)
print(new_t) #Take elements in the tuple and return a new sorted list
#(does not sort the tuple itself).

[1, 2, 3, 4, 5]

In [58]: #get the largest element in a tuple


t = (2, 5, 1, 6, 9)

print(max(t))

In [59]: #get the smallest element in a tuple


print(min(t))

In [60]: #get sum of elments in the tuple


print(sum(t))

23

Sets
-> A set is an unordered collection of items. Every element is unique (no duplicates).

-> The set itself is mutable. We can add or remove items from it.

-> Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.

Set Creation
In [61]: #set of integers
s = {1, 2, 3}
print(s)

#print type of s
print(type(s))

{1, 2, 3}
<class 'set'>

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 14/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [62]: #set doesn't allow duplicates. They store only one instance.
s = {1, 2, 3, 1, 4}
print(s)

{1, 2, 3, 4}

In [63]: #we can make set from a list


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

{1, 2, 3}

In [64]: #initialize a set with set() method


s = set()

print(type(s))

<class 'set'>

Add element to a Set


In [65]: #we can add single element using add() method and
#add multiple elements using update() method
s = {1, 3}

#set object doesn't support indexing


print(s[1]) #will get TypeError

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-65-22d0618a89be> in <module>
4
5 #set object doesn't support indexing
----> 6 print(s[1]) #will get TypeError

TypeError: 'set' object does not support indexing

In [66]: #add element


s.add(2)
print(s)

{1, 2, 3}

In [67]: #add multiple elements


s.update([5, 6, 1])
print(s)

{1, 2, 3, 5, 6}

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 15/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [68]: #add list and set


s.update([8, 9], {10, 2, 3})
print(s)

{1, 2, 3, 5, 6, 8, 9, 10}

Remove elements from a Set


In [69]: #A particular item can be removed from set using methods,
#discard() and remove().

s = {1, 2, 3, 5, 4}
print(s)

s.discard(4) #4 is removed from set s

print(s)

{1, 2, 3, 4, 5}
{1, 2, 3, 5}

In [70]: #remove an element


s.remove(2)

print(s)

{1, 3, 5}

In [71]: #remove an element not present in a set s


s.remove(7) # will get KeyError

---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-71-fcd391652dec> in <module>
1 #remove an element not present in a set s
----> 2 s.remove(7) # will get KeyError

KeyError: 7

In [72]: #discard an element not present in a set s


s.discard(7)
print(s)

{1, 3, 5}

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 16/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [73]: #we can remove item using pop() method

s = {1, 2, 3, 5, 4}

s.pop() #remove random element

print(s)

{2, 3, 4, 5}

In [74]: s.pop()
print(s)

{3, 4, 5}

In [75]: s = {1, 5, 2, 3, 6}

s.clear() #remove all items in set using clear() method

print(s)

set()

Python Set Operations


In [76]: set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}

#union of 2 sets using | operator

print(set1 | set2)

{1, 2, 3, 4, 5, 6, 7}

In [77]: #another way of getting union of 2 sets


print(set1.union(set2))

{1, 2, 3, 4, 5, 6, 7}

In [78]: #intersection of 2 sets using & operator


print(set1 & set2)

{3, 4, 5}

In [79]: #use intersection function


print(set1.intersection(set2))

{3, 4, 5}

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 17/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [80]: #set Difference: set of elements that are only in set1 but not in set2

print(set1 - set2)

{1, 2}

In [81]: #use differnce function


print(set1.difference(set2))

{1, 2}

In [82]: """symmetric difference: set of elements in both set1 and set2


#except those that are common in both."""

#use ^ operator

print(set1^set2)

{1, 2, 6, 7}

In [83]: #use symmetric_difference function


print(set1.symmetric_difference(set2))

{1, 2, 6, 7}

In [84]: #find issubset()


x = {"a","b","c","d","e"}
y = {"c","d"}

print("set 'x' is subset of 'y' ?", x.issubset(y)) #check x is subset of y

#check y is subset of x
print("set 'y' is subset of 'x' ?", y.issubset(x))

set 'x' is subset of 'y' ? False


set 'y' is subset of 'x' ? True

Frozen Sets
Frozen sets has the characteristics of sets, but we can't be changed once it's assigned. While tuple
are immutable lists, frozen sets are immutable sets

Frozensets can be created using the function frozenset()

Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand,
frozensets are hashable and can be used as keys to a dictionary.

This datatype supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(),
issuperset(), symmetric_difference() and union(). Being immutable it does not have method that
localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 18/24
3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

add or remove elements.

In [85]: set1 = frozenset([1, 2, 3, 4])


set2 = frozenset([3, 4, 5, 6])

#try to add element into set1 gives an error


set1.add(5)

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-85-627ec1ce44a6> in <module>
3
4 #try to add element into set1 gives an error
----> 5 set1.add(5)

AttributeError: 'frozenset' object has no attribute 'add'

In [86]: print(set1[1]) # frozen set doesn't support indexing

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-86-5c8e05737e66> in <module>
----> 1 print(set1[1]) # frozen set doesn't support indexing

TypeError: 'frozenset' object does not support indexing

In [87]: print(set1 | set2) #union of 2 sets

frozenset({1, 2, 3, 4, 5, 6})

In [88]: #intersection of two sets


print(set1 & set2)

#or
print(set1.intersection(set2))

frozenset({3, 4})
frozenset({3, 4})

In [89]: #symmetric difference


print(set1 ^ set2)

#or
print(set1.symmetric_difference(set2))

frozenset({1, 2, 5, 6})
frozenset({1, 2, 5, 6})

Dictionary
localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 19/24
3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

Python dictionary is an unordered collection of items. While other compound data types have only
value as an element, a dictionary has a key: value pair.

Dict Creation
In [90]: #empty dictionary
my_dict = {}

#dictionary with integer keys


my_dict = {1: 'abc', 2: 'xyz'}
print(my_dict)

#dictionary with mixed keys


my_dict = {'name': 'student', 1: ['abc', 'xyz']}
print(my_dict)

#create empty dictionary using dict()


my_dict = dict()

my_dict = dict([(1, 'abc'), (2, 'xyz')]) #create a dict with list of tuples
print(my_dict)

{1: 'abc', 2: 'xyz'}


{'name': 'student', 1: ['abc', 'xyz']}
{1: 'abc', 2: 'xyz'}

Dict Access
In [91]: my_dict = {'name': 'abc', 'age': 27, 'address': 'india'}

#get name
print(my_dict['name'])

abc

In [92]: #if key is not present it gives KeyError


print(my_dict['degree'])

---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-92-ac4c061783ba> in <module>
1 #if key is not present it gives KeyError
----> 2 print(my_dict['degree'])

KeyError: 'degree'

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 20/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [93]: #another way of accessing key


print(my_dict.get('address'))

india

In [94]: #if key is not present it will give None using get method
print(my_dict.get('degree'))

None

Dict Add or Modify Elements


In [95]: my_dict = {'name': 'student', 'age': 20, 'address': 'india'}

#update name
my_dict['name'] = 'xyz'

print(my_dict)

{'name': 'xyz', 'age': 20, 'address': 'india'}

In [96]: #add new key


my_dict['degree'] = 'B.Tech'

print(my_dict)

{'name': 'xyz', 'age': 20, 'address': 'india', 'degree': 'B.Tech'}

Dict Delete or Remove Element


In [97]: #create a dictionary
my_dict = {'name': 'abc', 'age': 20, 'address': 'india'}

#remove a particular item


print(my_dict.pop('age'))

print(my_dict)

20
{'name': 'abc', 'address': 'india'}

In [98]: my_dict = {'name': 'abc', 'age': 20, 'address': 'india'}

#remove an arbitarty key


my_dict.popitem()

print(my_dict)

{'name': 'abc', 'age': 20}

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 21/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [99]: squares = {2: 4, 3: 9, 4: 16, 5: 25}

#delete particular key


del squares[2]

print(squares)

{3: 9, 4: 16, 5: 25}

In [100]: #remove all items


squares.clear()

print(squares)

{}

In [101]: squares = {2: 4, 3: 9, 4: 16, 5: 25}

#delete dictionary itself


del squares

print(squares) #NameError because dict is deleted

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-101-6fac7747ecad> in <module>
4 del squares
5
----> 6 print(squares) #NameError because dict is deleted

NameError: name 'squares' is not defined

Dictionary Methods
In [102]: squares = {2: 4, 3: 9, 4: 16, 5: 25}

my_dict = squares.copy()
print(my_dict)

{2: 4, 3: 9, 4: 16, 5: 25}

In [103]: #fromkeys[seq[, v]] -> Return a new dictionary with keys from seq and value equal
subjects = {}.fromkeys(['Math', 'English', 'Hindi'], 0)
print(subjects)

{'Math': 0, 'English': 0, 'Hindi': 0}

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 22/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [104]: subjects = {2:4, 3:9, 4:16, 5:25}


print(subjects.items()) #return a new view of the dictionary items (key, value)

dict_items([(2, 4), (3, 9), (4, 16), (5, 25)])

In [105]: subjects = {2:4, 3:9, 4:16, 5:25}


print(subjects.keys()) #return a new view of the dictionary keys

dict_keys([2, 3, 4, 5])

In [106]: subjects = {2:4, 3:9, 4:16, 5:25}


print(subjects.values()) #return a new view of the dictionary values

dict_values([4, 9, 16, 25])

In [107]: #get list of all available methods and attributes of dictionary


d = {}
print(dir(d))

['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc_


_', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt_
_', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len_
_', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'cle
ar', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefaul
t', 'update', 'values']

Dict Comprehension
In [108]: #Dict comprehensions are just like list comprehensions but for dictionaries

d = {'a': 1, 'b': 2, 'c': 3}


for pair in d.items():
print(pair)

('a', 1)
('b', 2)
('c', 3)

In [109]: #Creating a new dictionary with only pairs where the value is larger than 2
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
new_dict = {k:v for k, v in d.items() if v > 2}
print(new_dict)

{'c': 3, 'd': 4}

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 23/24


3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook

In [110]: #We can also perform operations on the key value pairs
d = {'a':1,'b':2,'c':3,'d':4,'e':5}
d = {k + 'c':v * 2 for k, v in d.items() if v > 2}
print(d)

{'cc': 6, 'dc': 8, 'ec': 10}

In [ ]:

localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 24/24

You might also like