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

Module_3

Module 3 covers Lists, Tuples, Sets, and Dictionaries in Python. It explains the characteristics, creation, indexing, slicing, and operations of Lists and Tuples, highlighting their differences and similarities. The module also includes examples for better understanding of these data structures.

Uploaded by

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

Module_3

Module 3 covers Lists, Tuples, Sets, and Dictionaries in Python. It explains the characteristics, creation, indexing, slicing, and operations of Lists and Tuples, highlighting their differences and similarities. The module also includes examples for better understanding of these data structures.

Uploaded by

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

Module -3

Lists, Tuples, Sets and Dictionaries


Module -3
Lists
• What is “LISTS?”
§A list is ordered collection of items or elements.
§A single variable identifies each element.
§A list is a linear data structure.
§Lists are referred to as Python arrays
§Data elements to be arranged in a sequential or linear fashion.
§The constituents of a list are referred to as items or elements.
§Each element identified by its index value

Table : Indexed Data Structure


• Properties of Lists
ØA List is mutable, means List’s contents may be altered.

ØLists in Python use zero based indexing

ØObjects of any kind can be found amongst them.

ØAn index provides quick and easy access to list items

ØThere is no cap on the number of sub-lists that can be encapsulated in a single list.

ØA list can be a wide range of sizes.


• Creating a “LISTS”
Syntax:
[<element 1>,<element 2>,…<element n>]

§We create a list by placing elements inside [ ] and separated by commas.

§A list can store elements of different types (integer, float, string, etc.) and can store duplicate
elements

Ex 1:ages = [19, 26, 23]


print(ages)
# Output:
[19, 26, 23]

Ex2: items =(5,6,7,8)


print(“items =“,list(items))
#output:
[5,6,7.8]
• Examples of list
Description
List
• Indexing the list
§ The list elements can be accessed using the “indexing” technique.

§ Syntax: name_of _the_list[index of the item to be accessed]

§ Lists are ordered collections with unique indexes for each item.
§ We can access the items in the list using this index number.

§To access the elements in the list from left to right, the index value starts from zero to (length of the list-1) can
be used.
• Accessing values of elements in a list
•To access an element , use brackets
Value[x]=0
Element = values[x]

• Examples: my_list = [10, 20, 'Jessa', 12.50, 'Emma']

print(my_list[1]) # accessing 2nd element of the list


# 20

print(my_list[4]) # accessing 5th element of the list


# 'Emma‘

print(my_list[-1]) # accessing last element of the list


# output 'Emma'

print(my_list[-2]) # accessing second last element of the list


# output 12.5

print(my_list[-4]) # accessing 4th element from last


# output 20
• List Slicing
§ Slicing a list implies, accessing a range of elements in a list using the slicing operator ( : )
§ The syntax for list slicing.
› listname[start_index : end_index : step] or listname[start:end]
› Two or three parameters can be used in slicing
 The start_index denotes the index position from where the slicing should begin.
Default value is Zero.
 The end_index parameter denotes the index positions till which the slicing should
be done. Default value is Zero.
 The step allows you to take each nth-element within
a start_index:end_index range
Example for slicing :
my_list = [10, 20, 'Jessa', 12.50, 'Emma', 25, 50]

# Extracting a portion of the list from 2nd till 5th element


print(my_list[2:5])

# Output
['Jessa', 12.5, 'Emma']
• We can also use slicing a list such as
§Extract a portion of the list
§Reverse a list
§Slicing with a step
§Slice without specifying start or end position

 EX1:my_list = [5, 8, 'Tom', 7.50, 'Emma']


print(my_list[:4]) # slice first four items
# Output: [5, 8, 'Tom', 7.5]

 Ex2:print(my_list[::2]) # print every second element with a skip count 2


# Output :[5, 'Tom', 'Emma']

 Ex3:print(my_list[::-1]) # reversing the list


# Output: ['Emma', 7.5, 'Tom', 8, 5]

 Ex4:print(my_list[3:]) # Without end_value stating from 3nd item to last item


# Output [7.5, 'Emma']
Operations in the LIST

• Depending on the requirement, lists can be manipulated based


on the problem. List manipulation can be done with the help of
operations.
• List are Python’s most widely used data types due to the
variety of operations they can perform.
Operations in the LIST
Concatenation + operator.

• It is a binary infix (+) operator .


• The concatenation of two lists means merging of two lists.
• If two lists are to be concatenated (+) then a new list that contains the
elements of the first list, followed by the elements of second list will be
generated.
• Syntax: List1 + List2
• Ex:
>>>my_list1 = [1, 2, 3]
>>>my_list2 = [4, 5, 6]
# Using + operator
>>>my_list3 = my_list1 + my_list2
>>>print(my_list3)
# Output [1, 2, 3, 4, 5, 6]
Repetition (*) operator
• Repetition (*) operator is used with an integer to specify the
number of copies the list is to be generated.
• “*” operator has different purpose
– With one list and one integer “*”replicates a list as many times as
integer allows.
– Generates new lists by appending several instances of the same list.

• Syntax: list1*Number
Repetition (*) operator
• Example for replication (*) operator
– print(“Python" * 3)
• #PythonPythonPython
– print(3 * "Hi")
• #HiHiHi
– print("7" * 3)
• #777
== operator for equality testing
• Python allows the comparison of two lists to see if they are exactly equal, meaning they
have the same elements, in the same order by using the “==“ operator.

• Example for equality


>>>[3,7,8,666] == [3,7,8,666]
True
>>>[red,green,yellow] == [c, python, c++]
False

• Example for inequality


>>>[3,7,8,666 ]!= [3,7,8,666]
False
>>>[red,green,yellow] != [c, python, c++]
True
Membership operator
Membership operator
Tuples
• Introduction to “Tuples”
– It is used to store a collection of elements that are arranged in a certain way and cannot be altered.
– It is versatile and powerful data structure since it carry components of any arbitrary data type(integer , text, float,
list,etc)
– Example: music playlists, browser bookmarks, email messages and collection of videos that one may access
through a streaming service.
Tuples
• Tuple has the following characteristics

– Tuples are immutable and hence can be use as keys for the dictionary
– Ordered: Tuples are part of sequence data types, which means they hold the order of the data insertion. It
maintains the index value for each item.
– Immutable :Tuples are unchangeable, which means that we cannot add or delete items to
the tuple after creation.
– Heterogeneous: Tuples are a sequence of data of different data types (like integer, float, list, string, etc;) and
can be accessed through indexing and slicing.
– Contains Duplicates: Tuples can contain duplicates, which means they can have items with
the same value.
– Iteration of tuples, compared to lists is considerably faster.
– Tuples are efficient.
Tuples
• Why tuples prefered over Lists?
– Lists and tuples are both utilized in contexts that are analogous to one another.
• Similarities between Lists and Tuples
– Hold heterogeneous types
– Can have duplicate elements
– Elements can accessed using indexing and slicing
– Both have many functions such as max,min,and len
• Dissimilarities between Lists and Tuples
Lists Tuples
Lists are mutable Tuples are immutable
Lists elements are enclosed by square brackets Tuples are items that are separated by commas
enclosed by brackets()

Lists elements can be accessed using many functions Tuples elements too can be accessed by many
and methods functions and methods, but in lesser, because tuples
are immutable.
Tuples
• Creating a Tuples
– We can create a tuple using the two ways
– Using parenthesis (): A tuple is created by enclosing comma-separated items inside rounded
brackets.
– Syntax: Variable_Name = (<element1>,<element2>,…<elementn>)

– Using a tuple() constructor: Create a tuple by passing the comma-separated items inside
the tuple().
Syntax:Variable_Name=tuple(<sequence>)
Creating a Tuples
• Create a tuple using ()
# number tuple
number_tuple = (10, 20, 25.75)
print(number_tuple)
Print(type(number_tuple))
# Output (10, 20, 25.75)
<class ‘tuple’>

# string tuple
string_tuple = ('Jessa', 'Emma', 'Kelly')
print(string_tuple)
# Output ('Jessa', 'Emma', 'Kelly')

# mixed type tuple


sample_tuple = ('Jessa', 30, 45.75, [25, 78])
print(sample_tuple)
# Output ('Jessa', 30, 45.75, [25, 78])

#Tuple with duplicate elements


dup_tuple=(‘Jessa’, 10, ‘Jessa’, 20)
#output (‘Jessa’.10,’Jessa’,20)
Creating a Tuples
• Tuples can be created using tuple() constructor

# create a tuple using tuple() constructor


sample_tuple2 = tuple(('Jessa', 30, 45.75, [23, 78]))
print(sample_tuple2)
# Output ('Jessa', 30, 45.75, [23, 78])
Assignment, Packing and Unpacking
• One major uses of tuples is “tuple assignment”.
• For example, tuple assignment is as follows,
– x,y=10,20
– LHS is the tuple of variables and RHS is the tuple of expressions or values.
– Each value is assigned to the respective variables.
– The condition is that the number of variables on right and left has to be same.
• For ex, x.y=10,20,30 results error
– If expressions are given then, Python evaluates the expression before assigning them.
• Packing and Unpacking(embedding)
– A tuple can also be created without using a tuple() constructor or enclosing the items inside the
parentheses. It is called the variable “Packing.”
– Variables on the LHS are variables associated with tuples. When tuples is created, one can assign
values to it. It is called “Packing”

# packing variables into tuple


tuple1 = 1, 2, "Hello"
print(tuple1)
# Output (1, 2, 'Hello')
print(type(tuple1))
# Output class 'tuple'

# unpacking tuple into variable


i, j, k = tuple1
# printing the variables
print(i, j, k)
# Output 1 2 Hello
Tuple
• Indexing and slicing in a Tuple:
– Accessing items of a Tuple:
– Tuple can be accessed through indexing and slicing

– Accessing tuple using the following two ways

• Using indexing: Access any item from a tuple using its index number
• Using slicing: Access a range of items from a tuple
Indexing and slicing in a Tuple
• Indexing:
– We can access an item of a tuple by using its index number inside the index
operator [] and this process is called “Indexing”.

– Syntax: name_of_the_tuple[indexof the item to be accessed]

Example:
tuple1 = ('P', 'Y', 'T', 'H', 'O', 'N')
for i in range(4):
print(tuple1[i])
#Output
P
Y
T
H

• Illustration of IndexError
– Tuple1= (1,3,4)
– Tuple1[6]
# output: IndexError:tuple index out of range
• Negative Indexing
– The index values can also be negative, with the last but the first items having the index value as -1
and second last -2 and so on.
– Example:
tuple1 = ('P', 'Y', 'T', 'H', 'O', 'N')
# Negative indexing
# print last item of a tuple
print(tuple1[-1])
#N
# print second last
print(tuple1[-2])
#O
• Slicing:
– We can even specify a range of items to be accessed from a tuple using the technique called
‘Slicing.’
– The operator used is ':'.
– Syntax:
• Tuple_variable[start:stop:step] or
• Tuple_variable[start:stop]

• Example:
• tuple1 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
• # slice a tuple with start and end index number
• print(tuple1[1:5])
• # Output (1, 2, 3, 4)
• # slice a tuple without start index
tuple1 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(tuple1[:5])
# Output (0, 1, 2, 3, 4)

• # slice a tuple without end index


print(tuple1[6:])
# Output (6, 7, 8, 9, 10)

• # slice a tuple using negative indexing


tuple1 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(tuple1[-5:-1])
# Output (6, 7, 8, 9)

# iterate a tuple using negative indexing


for i in range(-6, 0):
print(tuple1[i], end=", ")
# Output P, Y, T, H, O, N,
Operations in Tuples
• In Python, Tuple is a sequence.
– We can concatenate two tuples with “+” operator
– Concatenate multiple copies of a tuple with "*" operator.
– The membership operators "in" and "not in" work with tuple object.
• len():
– This function is used to determined with the help of len()
– Syntax :
• Len(tuple_variable)
– The return value is an intger containing the total number of tuple items.
– Example:
• tup1= (1,2,3,4,5,6,7)
• len(tup1)
• Output: 7
• Summarization of Tuple operation
• Concatenation “+”
– Using the addition operator, with two or more tuples, adds up all the
elements into a new tuple.
– Syntax:
• tuple_new=tuple_variable1 + tuple_variable2
– Example1:
• >>> t = (2, 5, 0) + (1, 3) + (4,)
• >>> print (t);
• Output:
• (2, 5, 0, 1, 3, 4)
– Example2:
• >>> t1 = (2, 5, 0)
• >>> t1 + (8,)
• (2, 5, 0,8)
• Multiplication(Replication) operator:
– Multiplying a tuple by any integer, x will simply create another tuple
with all the elements from the first tuple being repeated x number of
times.
– Example1:
• >>> t = (2, 5)
• >>> print (t*3);
• Output:
• (2, 5, 2, 5, 2, 5)
• Membership operator
– This operator determines whether a value is a set member.
– Example1:
– >>> t = (1, 2, 3, 6, 7, 8)
– >>> 2 in t
– >>> 5 in t
– Output:
• True
• False

– >>> t = (1, 2, 3, 6, 7, 8)
– >>> 2 not in t
– >>> 5 not in t
• False
• True
Sets
• Introduction to sets:
– A set in Python is a Python data structure that stores a collection of
unique elements.
– Python set is similar mathematical sets, but they are part of the
Python standard library.
Characteristics of a Sets
– Unordered:
• The items in the set are unordered, unlike lists, i.e., it will not maintain the order in
which the items are inserted. The items will be in a different order each time when
we access the Set object.
– Unchangeable:
• Set items must be immutable. We cannot change the set items, i.e., We cannot
modify the items’ value.
• But we can add or remove items to the Set. A set itself may be modified, but the
elements contained in the set must be of an immutable type.
• Lists can’t be set elements, but tuples can.
– Unique:
• There cannot be two items with the same value in the set.Iin set duplicate items
not allowed
– Set does not support indexing
Advantages of Sets
• Sets have a solid mathematical foundation, such as set union and
set intersection.
• Searching for an element in a list takes lots of time. But searching
for element in sets is quickly.
• Sets not allow duplicate elements, like list. So does not effect the
application.
Creating a Set
• Using curly brackets:
• Python sets are constructed by just enclosing all the data
items inside the curly brackets {}.
• The individual values are comma-separated.
• Syntax:
Set_variable = {<element>, <element>,…. <element>}
– Set items are unordered, unchangeable, and do not allow duplicate
values.
Creating a Set
• Example1:
>>>s1 = {}
>>>Type(s1)

Output:
<class ‘dict’>

• Example2:
# set of mixed types intger, string, and floats
>>>sample_set = {'Mark', 'Jessa', 25, 75.25}
>>>print(sample_set)

# Output:
{25, 'Mark', 75.25, 'Jessa'}
Creating a Set
• Using set() constructor:
– The set object is of type class 'set'.
– Create a set by calling the constructor of class ‘set’.
– The items we pass while calling are of the type iterable.
– We can pass items to the set constructor inside double-rounded brackets.
§ Example:
# create a set using set constructor
book_set = set(("Harry Potter", "Angels and Demons", "Atlas Shrugged"))
print(book_set)
§ # output
{'Harry Potter', 'Atlas Shrugged', 'Angels and Demons'}
Creating a Set
• Examples of sets:
– A set created from tuples: st_1 =set((‘tiger’,’lion’))
o/p:{‘tiger’,’lion’}
– A set created from strings: ss_2 = ‘ heeello’
set (ss_2)
o/p: {'h', 'o', 'l', 'e'}(removes duplicate)
– A set with range()function:
>>>X = set(range(0,122,10))
>>>print(X)
o/p: {0, 100, 70, 40, 10, 110, 80, 50, 20, 120, 90, 60, 30}
Basic operations in Sets:
• All the operations that could be performed in a mathematical set
could be done with Python sets.
• We can perform set operations using the operator or the built-in
methods defined in Python for the Set.

– The length or size of the set is determined by using the built –in len() function.
– Syntax: len(set_variable)
– Example:
>>>color_set = {'violet', 'indigo', 'blue', 'green', 'yellow‘}
>>>print(len(color_set))
Output:
5
Membership operator in set

• Example:
>>>color_set = {'violet', 'indigo', 'blue', 'green', 'yellow'}
>>>'violet‘ in color_set
True
>>>’tiger’ not in color_set
True
Sets and frozen sets
Adding elements to sets
• To add one item to a set use the add() method.
• Syntax : set_variable.add(<iterator>)
• The function returns no value. It is added if the specified value
does not exist in the set
• Example:
>>>thisset = {"apple", "banana", "cherry"}
>>>thisset.add("orange")
print(thisset)
O/P: {"apple", "banana", "cherry“, ”orange”}
Adding elements to sets
• To add items from another set into the current set, use
the update() method.

• Syntax: set_variable.update(iterable)

• Example:
>>>thisset = {"apple", "banana", "cherry"}
>>>tropical = {"pineapple", "mango", "papaya"}
>>>thisset.update(tropical)
print(thisset)
O/P: {'apple', 'mango', 'cherry', 'pineapple', 'banana', 'papaya'}
Deletion of elements from Set
• Four methods to the deletion of elements in sets
Deletion of elements from Set
• Removal of an element in set:
– The remove(element) removes specific element and returns it.
– If specified element is not present in the set the method raises an keyError
exception.
– Case sensitive: element name should as same as in set
• Syntax: set_variable.remove(element)
• Example:
– tropical = {"pineapple", "mango", "papaya"}
– tropical.remove(“mango”)
– print(tropical)
– {"pineapple“, "papaya"}
Deletion of elements from Set
• Discarding an element in a set:
– The method discard() is used to discard an element of the set similar to the
remove ().
– It does not raise an error, and the set remains unchanged if element does not
exist in set.
• Syntax: set_variable.discard(element)
– Example:
– X = {1,8,90,100}
– X.discard(100)
– X
– {8,1,90}
Deletion of elements from Set
• Removing a random element in a set
– The method pop() has no input parameters and returns a random
element and removed element or typeError if the set is empty.
– Syntax: set_variable.pop(element)
– Example:
– >>>X = {1,8,90,100}
– >>>item=X.pop()
– >>>item
– Output: 8
Deletion of elements from Set
• Deletion of a set:
– A set deletion can be done using the set clear methd.
– Syntax: set_variable.clear()
– The method removes all the elements from the set.
– It does not take any parameters or return any values.
– Example:
– tropical = {"pineapple", "mango", "papaya"}
– tropical.clear()
– tropical
– o/p:set()
Deletion of elements from Set
• Set copy:
– The set.copy() method returns a shallow copy of the set.
– The result is superficial replica of the set.
– Also use = operator
• Syntax: set_variable1.copy(set_variable2)
– Example:
– >>>X = {1,8,90,100}
– >>>Y= X.copy()
– >>>Y
– O/P: {1,8,90,100}
– >>>Z=X
– >>>Z
– {1,8,90,100}
Introduction to Dictionary
• What is “Dictionary”?
– A kind of associative array that is useful for lookup.
– It is a collection of unorganized items.
– It has a key-value pair for an element.
• Example: Telephone directory, to find the phone number(value) when we know the
name(Key) associated with it.

• Syntax: Dictionary_name = {key:value}

– Key: User-defined index or unique identifier that helps lookup.


– Value: Key related information
Introduction to Dictionary
• Characteristics of “Dictionary”:
– Dictionary keys are unique to each other.
– Keys must be of an immutable data type( texts, number or tuple)
– Values can be any kind. May be unique or mutable.
– Each shall occur only once in the dictionary.
– The ordering of the words does not matter.
Creating Dictionary
• There are following three ways to create a dictionary.
– Using curly brackets: The dictionaries are created by enclosing the comma-
separated Key: Value pairs inside the {} curly brackets. The colon ‘:‘ is used to
separate the key and value in a pair.
– Using dict() constructor: Create a dictionary by passing the comma-separated key:
value pairs inside the dict().
– Using fromKeys(): creates a new dictionary with keys from sequence and values set
to value
Creating Dictionary
# Create a dictionary using {}
>>>person = {"name": "Jessa", "country": "USA", "telephone": 1178}
>>>print(person)
# Output: {'name': 'Jessa', 'country': 'USA', 'telephone': 1178}

# Create a dictionary using dict()


>>>person = dict({"name": "Jessa", "country": "USA", "telephone": 1178})
>>>print(person)
# Output: {'name': 'Jessa', 'country': 'USA', 'telephone': 1178}

# Create dictionary using fromKey()


>>>keys ={‘12’,’23’,’1’,’5’,’7’,’11’}
>>>values=0
>>>sample = dict.fromKeys(key,value)
>>>print(sample)
#Output: {‘12’:0,’23’:0,’1’:0,’5’:0,’7’:0,’11’:0}
Creating Dictionary
# Create a dictionary from sequence having each item as a pair
>>>person = dict([("name", "Mark"), ("country", "USA"), ("telephone", 1178)])
>>>print(person)
#Output:{'name': 'Mark', 'country': 'USA', 'telephone': 1178}

# create dictionary with mixed keys


# first key is string and second is an integer
>>>sample_dict = {"name": "Jessa", 10: "Mobile"}
>>> print(sample_dict)
# output {'name': 'Jessa', 10: 'Mobile'}

# create dictionary with value as a list


>>>person = {"name": "Jessa", "telephones": [1178, 2563, 4569]}
>>>print(person)
# output {'name': 'Jessa', 'telephones': [1178, 2563, 4569]}
Basic dictionary operations
• Membership operator
– in
– not in

• Accessing dictionary elements


– Use the key to retrieve the value
– Use the get() method

• Can get all the values in a single go using method listed below:
– dict.keys() isolates keys
– dict.values() isolates values
– dict.items() returns items in a list format of (key,value) tuple pair
Basic dictionary operations
• Example for Membership operator
>>>d_state={1:’Delhi’, 2:’Mumbai’,3:’Chennai’,4:’Kolkatta’}
>>>1 in d_state
Output: True

>>>1 not in d_state


Output: False

• Accessing dictionary elements


1.#Use the key to retrieve the value
>>>d_state={1:’Delhi’, 2:’Mumbai’,3:’Chennai’,4:’Kolkatta’}
>>>d_state[1]
Output: ‘Delhi’

2.#Use the get() method: Syntax: dict.get(key, default= None)


>>>d_state={1:’Delhi’, 2:’Mumbai’,3:’Chennai’,4:’Kolkatta’}
>>>print(d_state.get(1))
Output: Delhi
Basic dictionary operations
 Can get all the values in a single go using method listed below:

 dict.keys() isolates keys:


>>>d_state={1:’Delhi’, 2:’Mumbai’,3:’Chennai’,4:’Kolkatta’}
>>>d_state.keys()
 o/p:dict_keys([1, 2, 3, 4])

 dict.values() isolates values


>>>d_state={1:’Delhi’, 2:’Mumbai’,3:’Chennai’,4:’Kolkatta’}
>>>d_state.values()
 o/p:dict_values(['Delhi', 'Mumbai', 'Chennai', 'Kolkatta'])

 dict.items()
>>>d_state={1:’Delhi’, 2:’Mumbai’,3:’Chennai’,4:’Kolkatta’}
>>>d_state.items()
 o/p:dict_items([(1, 'Delhi'), (2, 'Mumbai'), (3, 'Chennai'), (4, 'Kolkatta')])
Operation on Python dictionary
• Adding an element
– We can add new items to the dictionary using the following two ways.
1.Using key-value assignment: Using a simple assignment statement where value can be assigned directly to
the new key.
• Syntax: dict[key] = value

2.Using update() Method: In this method, the item passed inside the update() method will be inserted into
the dictionary. The item can be another dictionary or any iterable like a tuple of key-value pairs.
• Syntax: dict.update([other]) or dict.update(dict2)
Operation on Python dictionary
Example: 1.Using key-value assignment
>>>person = {"name": "Jessa", 'country': "USA", "telephone": 1178}
# update dictionary by adding 2 new keys
>>> person["weight"] = 50 # using new key
>>>person. update({"height": 6}) # using update method

# print the updated dictionary


>>>print(person)

#output: {'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50,'height’:6}


Remove the elements of the dictionary
1. pop() method: Removes the item with the given key and returns the value.
• Example:
>>>person = {'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50, 'height': 6}

# Remove key 'telephone' from the dictionary


deleted_item = person.pop('telephone')
print(deleted_item)
# output: 1178

# display updated dictionary


print(person)
# Output: {'name': 'Jessa', 'country': 'USA', 'weight': 50}
Remove the elements of the dictionary
• popitem():Removes arbitrary item and returns an arbitrary element(key,value) pair from
the dictionary.
– Syntax:dict.popitem()
• Example:
>>>person = {'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50, 'height': 6}
# Remove last inserted item from the dictionary
>>> deleted_item = person.popitem()
>>> print(deleted_item)
# output ('height', 6)
# display updated dictionary
>>>print(person)
# Output {'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50}
Remove the elements of the dictionary
• del():Used to delete an individual item. Also used to delete the entire dictionary
– Syntax: del()

– Example:
>>>person={'name': 'Jessa', 'country': 'USA', 'weight': 50}
# delete key 'weight'
>>>del person['weight']
# display updated dictionary
>>>print(person)
# Output {'name': 'Jessa', 'country': 'USA'}

>>>del person
print(person)
Output: NameError
Remove the elements of the dictionary

• clear(): Removes all the items from the dictionary.


– Syntax: dict.clear()
– Example:
>>>person={'name': 'Jessa', 'country': 'USA', 'weight': 50}
# remove all item (key-values) from dict
>>>person.clear()
# display updated dictionary
>>>print(person)
# {}
Copying the elements of the dictionary
• There are numerous ways to clone a dictionary:
– 1.Element-by-element dictionary cloning: Every element pointed to key is copied to
a new dictionary. A shallow copy is created without affect the original dictionary.

– 2. Using the “= operator” to Copy a Dictionary in Python: Quick way to copy a


dictionary in Python using the ‘=’ operator.

– 3.Dictionary.copy(): Copies a dictionary shallowly. Original dictionary will stay


untouched when changes made. copy(): Creates new dictionary with a copy of the
references from the original dictionary.
– Syntax: dict.copy()
Copying the elements of the dictionary
1.Element-by-element dictionary cloning
#given dictionary
Output:
dict1={0:'1',1:'2',3:[1,2,3]}
print("Given Dictionary:",dict1)
Given Dictionary: {0: '1', 1: '2', 3: [1,
#new dictionary
2, 3]}
dict2={}
New copy: {0: '1', 1: '2', 3: [1, 2, 3]}
for i in dict1:
dict2[i]=dict1[i] #element by element copying
Updated copy: {0: '1', 1: 33, 3: [1,
'22', 3]}
print("New copy:",dict2)
Given Dictionary: {0: '1', 1: '2', 3: [1,
#Updating dict2 elements and checking the change in
'22', 3]}
dict1
dict2[1]=33
dict2[3][1]='22' #list item updated
print("Updated copy:",dict2)
print("Given Dictionary:",dict1)
Copying the elements of the dictionary
2. Using the = operator to Copy a Dictionary in Python

#given dictionary
dict1={1:'a',2:'b',3:[11,22,33]}
print("Given Dictionary:",dict1)
#new dictionary Output:
dict2=dict1 #copying using = operator Given Dictionary: {1: 'a', 2: 'b', 3: [11, 22, 33]}
print("New copy:",dict2)
New copy: {1: 'a', 2: 'b', 3: [11, 22, 33]}
#Updating dict2 elements and checking
the change in dict1 Updated copy: {1: 33, 2: 'b', 3: [11, 22, '44']}
Given Dictionary {1: 33, 2: 'b', 3: [11, 22,
dict2[1]=33
'44']}
dict2[3][2]='44' #list item updated

print("Updated copy:",dict2)
print("Given Dictionary:",dict1)
Copying the elements of the dictionary
• 3.Dictionary.copy():
#given dictionary
dict1={ 10:'a', 20:[1,2,3], 30: 'c'}
print("Given Dictionary:",dict1) Output:
#new dictionary
dict2=dict1.copy() #copying using copy() Given Dictionary: {10: 'a', 20: [1, 2, 3], 30: 'c'}
method New copy: {10: 'a', 20: [1, 2, 3], 30: 'c'}
print("New copy:",dict2)
Updated copy: {10: 10, 20: [1, 2, '45'], 30: 'c'}
Given Dictionary: {10: 'a', 20: [1, 2, '45'], 30: 'c'}
#Updating dict2 elements and checking the
change in dict1
dict2[10]=10
dict2[20][2]='45' #list item updated

print("Updated copy:",dict2)
print("Given Dictionary:",dict1)
Sort dictionary
• The built-in method sorted() will sort the keys in the dictionary and returns a sorted list.
• In case we want to sort the values we can first get the values using the values() and then
sort them.

• The sorted() function takes an iterable as the main argument, with two optional keyword-
only arguments—a key function and a reverse Boolean value.

– Syntax: sorted(iterable[,key=None][,reverse=False])

• iterable: The dictionary (or any other iterable).

• Key(optional):- A function to specify the criteria for sorting (e.g., by keys, by values).
i.e normal function identifier or a lambda function(anonymous function)
• Reverse(optional):- If set to True, sorts in descending order. And reverse= False just
sort in ascending order
Sort dictionary
Example:
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 7, "Best" : 2, "for" : 9, "geeks" : 8}
# using items() to get all items
# lambda function is passed in key to perform sort by key
# passing 2nd element of items()
# adding "reversed = True" for reversed order
res = {key: val for key, val in sorted(test_dict.items(), key = lambda x: x[1], reverse = True)}
# printing result
print("Result dictionary sorted by values ( in reversed order ) : " + str(res))

o/p:
Result dictionary sorted by values ( in reversed order ):{'for': 9, 'geeks': 8, 'is': 7, 'Gfg': 5, 'Best': 2}
Example 1: Sorting by Keys (Default)

• When you use sorted() on a dictionary, it sorts by the dictionary's keys by


default.

• In this example, sorted() only returns a sorted list of keys, not the
dictionary itself.
Example 2: Sorting Dictionary Items by Keys
• To sort a dictionary by its keys and keep both keys and values, you can use the
items() method.
Example 3: Sorting by Values
• To sort by values, you can use the key argument.

• To sort by keys:-
Note:
• The key=lambda item: item[1] tells Python to sort based on the
second item in each key-value pair, which are the values.
Example 4: Sorting in Reverse Order
• You can use the reverse=True parameter to sort in descending order.
Nested Dictionaries
• A dictionary can contain dictionaries, this is called nested dictionaries.
Access Items in Nested Dictionaries
• To access items from a nested dictionary, you use the name of the dictionaries,
starting with the outer dictionary:
• Example: Print the name of child 2:
•Nested dictionaries are dictionaries that have one or more dictionaries as their
members. It is a collection of many dictionaries in one dictionary.
# address dictionary to store person address

address = {"state": "Texas", 'city': 'Houston'}


# dictionary to store person details with address as a nested dictionary
person = {'name': 'Jessa', 'company': 'Google', 'address': address}
# Display dictionary
print("person:", person)
# Get nested dictionary key 'city‘
print("City:", person['address']['city'])
# Iterating outer dictionary
print("Person details")
for key, value in person.items():
if key == 'address':
# Iterating through nested dictionary Output:
print("Person Address") person: {'name': 'Jessa', 'company': 'Google', 'address': {'state':
for nested_key, nested_value in value.items(): 'Texas', 'city': 'Houston'}}
City: Houston
print(nested_key, ':', nested_value)
Person details name: Jessa company: Google
else:
Person Address state: Texas city : Houston
print(key, ':', value)
Looping over a dictionary
• We can iterate through the individual member dictionaries using nested for-
loop with the outer loop for the outer dictionary and inner loop for retrieving
the members of the collection.
• Syntax: for key,value in mydict.items():
print(key,value)
• There are many ways to loop over a dictionary
– Accessing both keys and value deprived of items
– Accessing key using the build.keys()
Example
Output

You might also like