SlideShare a Scribd company logo
4
Most read
5
Most read
8
Most read
Tuples: Tuple Basics, Operations, Methods, Packing and Unpacking, Tuple assignment,
tuple as return value; Dictionaries: Dictionary Basics, Operations, Methods, Aliasing
and Copying with Dictionaries, Nested Dictionaries
Tuple:
UNIT IV
ADVANCED DATATYPES
❖ A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
❖ A tuple is an immutable list. i.e. once a tuple has been created, you can't add
elements to a tuple or remove elements from the tuple.
❖ But tuple can be converted into list and list can be converted in to tuple.
methods example description
list( ) >>> a=(1,2,3,4,5)
>>> a=list(a)
>>> print(a)
[1, 2, 3, 4, 5]
it convert the given tuple
into list.
tuple( ) >>> a=[1,2,3,4,5]
>>> a=tuple(a)
>>> print(a)
(1, 2, 3, 4, 5)
it convert the given list into
tuple.
Benefit of Tuple:
❖ Tuples are faster than lists.
❖ If the user wants to protect the data from accidental changes, tuple can be used.
❖ Tuples can be used as keys in dictionaries, while lists can't.
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
Operations examples description
Creating a tuple >>>a=(20,40,60,”apple”,”ball”)
Creating the tuple with
elements of different data
types.
Indexing
>>>print(a[0])
20
>>> a[2]
60
Accessing the item in the
position 0
Accessing the item in the
position 2
Slicing >>>print(a[1:3])
(40,60)
Displaying items from 1st
till 2nd.
Concatenation >>> b=(2,4)
>>>print(a+b)
>>>(20,40,60,”apple”,”ball”,2,4)
Adding tuple elements at
the end of another tuple
elements
Repetition >>>print(b*2)
>>>(2,4,2,4)
repeating the tuple in n no
of times
Membership
>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
True
>>> 100 in a
False
>>> 2 not in a
False
Returns True if element is
present in tuple. Otherwise
returns false.
Comparison
>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4)
>>> a==b
False
>>> a!=b
True
Returns True if all elements
in both elements are same.
Otherwise returns false
Tuple methods:
❖ Tuple is immutable so changes cannot be done on the elements of a tuple once it
is assigned.
methods example description
a.index(tuple) >>> a=(1,2,3,4,5)
>>> a.index(5)
4
Returns the index of the
first matched item.
a.count(tuple) >>>a=(1,2,3,4,5)
>>> a.count(3)
1
Returns the count of the
given element.
Tuple Assignment:
>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3
Tuple as return value:
len(tuple) >>> len(a)
5
return the length of the
tuple
min(tuple) >>> min(a)
1
return the minimum
element in a tuple
max(tuple) >>> max(a)
5
return the maximum
element in a tuple
del(tuple) >>> del(a) Delete the entire tuple.
❖ Tuple assignment allows, variables on the left of an assignment operator and
values of tuple on the right of the assignment operator.
❖ Multiple assignment works by creating a tuple of expressions from the right hand
side, and a tuple of targets from the left, and then matching each expression to a
target.
❖ Because multiple assignments use tuples to work, it is often termed tuple
assignment.
Uses of Tuple assignment:
❖ It is often useful to swap the values of two variables.
Example:
Swapping using temporary variable: Swapping using tuple assignment:
a=20
b=50
temp = a
a = b
b = temp
print("value after swapping is",a,b)
a=20
b=50
(a,b)=(b,a)
print("value after swapping is",a,b)
Multiple assignments:
Multiple values can be assigned to multiple variables using tuple assignment.
❖ A Tuple is a comma separated sequence of items.
❖ It is created with or without ( ).
Dictionaries:
❖ A function can return one value. if you want to return more than one value from a
function. we can use tuple as return value.
Example1: Output:
def div(a,b):
r=a%b
q=a//b
return(r,q)
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
enter a value:4
enter b value:3
reminder: 1
quotient: 1
Example2: Output:
def min_max(a):
small=min(a)
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)
smallest: 1
biggest: 6
Tuple as argument:
❖ The parameter name that begins with * gathers argument into a tuple.
Example: Output:
def printall(*args):
print(args)
printall(2,3,'a')
(2, 3, 'a')
❖ Dictionary is an unordered collection of elements. An element in dictionary has a
key: value pair.
❖ All elements in dictionary are placed inside the curly braces i.e. { }
❖ Elements in Dictionaries are accessed via keys and not by their position.
❖ The values of a dictionary can be any data type.
❖ Keys must be immutable data type (numbers, strings, tuple)
Operations on dictionary:
1. Accessing an element
2. Update
Methods in dictionary:
3. Add element
4. Membership
Operations Example Description
Creating a
dictionary
>>> a={1:"one",2:"two"}
>>> print(a)
{1: 'one', 2: 'two'}
Creating the dictionary with
elements of different data types.
accessing an
element
>>> a[1]
'one'
>>> a[0]
KeyError: 0
Accessing the elements by using
keys.
Update >>> a[1]="ONE"
>>> print(a)
{1: 'ONE', 2: 'two'}
Assigning a new value to key. It
replaces the old value by new value.
add element >>> a[3]="three"
>>> print(a)
{1: 'ONE', 2: 'two', 3: 'three'}
Add new element in to the
dictionary with key.
membership a={1: 'ONE', 2: 'two', 3: 'three'}
>>> 1 in a
True
>>> 3 not in a
False
Returns True if the key is present in
dictionary. Otherwise returns false.
Method Example Description
a.copy( ) a={1: 'ONE', 2: 'two', 3: 'three'}
>>> b=a.copy()
>>> print(b)
{1: 'ONE', 2: 'two', 3: 'three'}
It returns copy of the
dictionary. here copy of
dictionary ’a’ get stored
in to dictionary ‘b’
a.items() >>> a.items()
dict_items([(1, 'ONE'), (2, 'two'), (3,
'three')])
Return a new view of
the dictionary's items. It
displays a list of
dictionary’s (key, value)
tuple pairs.
a.keys() >>> a.keys()
dict_keys([1, 2, 3])
It displays list of keys in
a dictionary
a.values() >>> a.values()
dict_values(['ONE', 'two', 'three'])
It displays list of values
in dictionary
a.pop(key) >>> a.pop(3)
'three'
>>> print(a)
{1: 'ONE', 2: 'two'}
Remove the element
with key and return its
value from the
dictionary.
setdefault(key,value) >>> a.setdefault(3,"three")
'three'
>>> print(a)
{1: 'ONE', 2: 'two', 3: 'three'}
>>> a.setdefault(2)
'two'
If key is in the
dictionary, return its
value. If key is not
present, insert key with
a value of dictionary and
return dictionary.
a.update(dictionary) >>> b={4:"four"}
>>> a.update(b)
>>> print(a)
{1: 'ONE', 2: 'two', 3: 'three', 4: 'four'}
It will add the dictionary
with the existing
dictionary
fromkeys() >>> key={"apple","ball"}
>>> value="for kids"
>>> d=dict.fromkeys(key,value)
>>> print(d)
{'apple': 'for kids', 'ball': 'for kids'}
It creates a dictionary
from key and values.
len(a) a={1: 'ONE', 2: 'two', 3: 'three'}
>>>lena(a)
3
It returns the length of
the list.
clear() a={1: 'ONE', 2: 'two', 3: 'three'}
>>>a.clear()
>>>print(a)
>>>{ }
Remove all elements
form the dictionary.
del(a) a={1: 'ONE', 2: 'two', 3: 'three'}
>>> del(a)
It will delete the entire
dictionary.
Aliasing(copying)in Dictionary:
❖ Creating a copy of a dictionary is called aliasing. When you create a copy, both
dictionary will be having same memory location.
❖ Changes in one dictionary will affect another dictionary.
❖ Aliasing refers to having different names for same dictionary values.
❖ In this a single dictionary object is created and modified using the subscript operator.
❖ When the first element of the dictionary named “a” is replaced, the first element of
the dictionary named “b” is also replaced.
❖ This type of change is what is known as a side effect. This happens because after
the assignment b=a, the variables a and b refer to the exact same dictionary object.
❖ They are aliases for the same object. This phenomenon is known as aliasing.
❖ To prevent aliasing, a new object can be created and the contents of the original can
be copied which is called cloning.
Cloning:
❖ To avoid the disadvantages of copying we are using cloning.
❖ Creating a copy of a same dictionary of elements with two different memory
locations is called cloning.
❖ Changes in one dictionary will not affect locations of another dictionary.
❖ Cloning is a process of making a copy of the dictionary without modifying the
original dictionary.
❖ In dictionary we can use copy() method for cloning.
❖ Slicing is not supported in the dictionary to reduce aliasing effect.
Difference between List, Tuples and dictionary:
List Tuples Dictionary
A list is mutable A tuple is immutable A dictionary is mutable
Lists are dynamic Tuples are fixed size in nature In values can be of any
data type and can
repeat, keys must be of
immutable type
List are enclosed in
brackets[ ] and their
elements and size
can be changed
Tuples are enclosed in parenthesis ( )
and cannot be updated
Tuples are enclosed in
curly braces { } and
consist of key:value
Homogenous Heterogeneous Homogenous
Example:
List = [10, 12, 15]
Example:
Words = ("spam", "egss")
Or
Words = "spam", "eggs"
Example:
Dict = {"ram": 26, "abi":
24}
Access:
print(list[0])
Access:
print(words[0])
Access:
print(dict["ram"])
Can contain duplicate
elements
Can contain duplicate elements.
Faster compared to lists
Cant contain duplicate
keys, but can contain
duplicate values
Slicing can be done Slicing can be done Slicing can't be done
Usage:
❖ List is used if a
collection of data that
doesnt need random
access.
❖ List is used when
data can be modified
frequently
Usage:
❖ Tuple can be used when data
cannot be changed.
❖ A tuple is used in combination
with a dictionary i.e.a tuple might
represent a key.
Usage:
❖ Dictionary is used
when a logical
association between
key:value pair.
❖ When in need of fast
lookup for data, based
on a custom key.
❖ Dictionary is used
when data is being
constantly modified.

More Related Content

PDF
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
PDF
ESIT135 Problem Solving Using Python Notes of Unit-1 and Unit-2
PDF
Insertion Sort, Merge Sort. Time complexity of all sorting algorithms and t...
PPTX
ITE Course Unit 1Productivity Tools For An Engineers
PDF
Sorting Algorithms: Bubble Sort, Selection Sort,
PDF
Stack Applications : Infix to postfix conversion, Evaluation of postfix expre...
PPTX
Searching and Sorting Unit II Part I.pptx
PDF
Introduction to Stack, ▪ Stack ADT, ▪ Implementation of Stack using array, ...
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-1 and Unit-2
Insertion Sort, Merge Sort. Time complexity of all sorting algorithms and t...
ITE Course Unit 1Productivity Tools For An Engineers
Sorting Algorithms: Bubble Sort, Selection Sort,
Stack Applications : Infix to postfix conversion, Evaluation of postfix expre...
Searching and Sorting Unit II Part I.pptx
Introduction to Stack, ▪ Stack ADT, ▪ Implementation of Stack using array, ...

What's hot (20)

PPTX
ESIT135: Unit 3 Topic: functions in python
PPTX
Unit 1- Python- Features, Variables, Data Types, Operators and Expressions
PPTX
Fundamentals of Data Structure_Unit I.pptx
PPTX
list.pptx
PPTX
JAVASRIPT and PHP (Hypertext Preprocessor)
PPTX
ESIT135 : Unit 1 Python Basics Concepts
PPTX
Unit4-Basic Concepts and methods of Dictionary.pptx
PPTX
Unit-4 Basic Concepts of Tuple in Python .pptx
PDF
Python functions
PPTX
Dictionary in python
PPTX
Python Functions
PDF
Python lists & sets
PPT
C operator and expression
PPTX
Pointer arithmetic in c
PPTX
Doubly linked list
PPTX
Python-Functions.pptx
PPTX
Data Structures - Lecture 9 [Stack & Queue using Linked List]
PDF
9 python data structure-2
PDF
Python cheat-sheet
DOCX
Report 02(Binary Search)
ESIT135: Unit 3 Topic: functions in python
Unit 1- Python- Features, Variables, Data Types, Operators and Expressions
Fundamentals of Data Structure_Unit I.pptx
list.pptx
JAVASRIPT and PHP (Hypertext Preprocessor)
ESIT135 : Unit 1 Python Basics Concepts
Unit4-Basic Concepts and methods of Dictionary.pptx
Unit-4 Basic Concepts of Tuple in Python .pptx
Python functions
Dictionary in python
Python Functions
Python lists & sets
C operator and expression
Pointer arithmetic in c
Doubly linked list
Python-Functions.pptx
Data Structures - Lecture 9 [Stack & Queue using Linked List]
9 python data structure-2
Python cheat-sheet
Report 02(Binary Search)
Ad

Similar to ESIT135 Problem Solving Using Python Notes of Unit-3 (20)

PDF
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
PPTX
UNIT-4.pptx python for engineering students
PPTX
Python list tuple dictionary .pptx
PPTX
Python Dynamic Data type List & Dictionaries
PPTX
Chapter 3-Data structure in python programming.pptx
PPTX
UNIT 1 - Revision of Basics - II.pptx
PPTX
Tuples-and-Dictionaries.pptx
PPTX
Dictionary
PPTX
Python for Beginners(v3)
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
PDF
Python Variable Types, List, Tuple, Dictionary
PPTX
Python Lecture 11
PPTX
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
PPTX
DICTIONARIES (1).pptx
PPTX
Basic data structures in python
PPTX
Modulebajajajjajaaja shejjsjs sisiisi 4.pptx
PDF
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
PPTX
11 Introduction to lists.pptx
PDF
Python revision tour II
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
UNIT-4.pptx python for engineering students
Python list tuple dictionary .pptx
Python Dynamic Data type List & Dictionaries
Chapter 3-Data structure in python programming.pptx
UNIT 1 - Revision of Basics - II.pptx
Tuples-and-Dictionaries.pptx
Dictionary
Python for Beginners(v3)
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
Python Variable Types, List, Tuple, Dictionary
Python Lecture 11
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
DICTIONARIES (1).pptx
Basic data structures in python
Modulebajajajjajaaja shejjsjs sisiisi 4.pptx
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
11 Introduction to lists.pptx
Python revision tour II
Ad

Recently uploaded (20)

PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
Sustainable Sites - Green Building Construction
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PDF
Well-logging-methods_new................
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPT
Mechanical Engineering MATERIALS Selection
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
CH1 Production IntroductoryConcepts.pptx
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
additive manufacturing of ss316l using mig welding
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Sustainable Sites - Green Building Construction
Automation-in-Manufacturing-Chapter-Introduction.pdf
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
Well-logging-methods_new................
Foundation to blockchain - A guide to Blockchain Tech
Mechanical Engineering MATERIALS Selection
Embodied AI: Ushering in the Next Era of Intelligent Systems
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
CH1 Production IntroductoryConcepts.pptx
Operating System & Kernel Study Guide-1 - converted.pdf
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
R24 SURVEYING LAB MANUAL for civil enggi
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
UNIT 4 Total Quality Management .pptx
additive manufacturing of ss316l using mig welding

ESIT135 Problem Solving Using Python Notes of Unit-3

  • 1. Tuples: Tuple Basics, Operations, Methods, Packing and Unpacking, Tuple assignment, tuple as return value; Dictionaries: Dictionary Basics, Operations, Methods, Aliasing and Copying with Dictionaries, Nested Dictionaries Tuple: UNIT IV ADVANCED DATATYPES ❖ A tuple is same as list, except that the set of elements is enclosed in parentheses instead of square brackets. ❖ A tuple is an immutable list. i.e. once a tuple has been created, you can't add elements to a tuple or remove elements from the tuple. ❖ But tuple can be converted into list and list can be converted in to tuple. methods example description list( ) >>> a=(1,2,3,4,5) >>> a=list(a) >>> print(a) [1, 2, 3, 4, 5] it convert the given tuple into list. tuple( ) >>> a=[1,2,3,4,5] >>> a=tuple(a) >>> print(a) (1, 2, 3, 4, 5) it convert the given list into tuple. Benefit of Tuple: ❖ Tuples are faster than lists. ❖ If the user wants to protect the data from accidental changes, tuple can be used. ❖ Tuples can be used as keys in dictionaries, while lists can't. Operations on Tuples: 1. Indexing 2. Slicing 3. Concatenation 4. Repetitions 5. Membership 6. Comparison
  • 2. Operations examples description Creating a tuple >>>a=(20,40,60,”apple”,”ball”) Creating the tuple with elements of different data types. Indexing >>>print(a[0]) 20 >>> a[2] 60 Accessing the item in the position 0 Accessing the item in the position 2 Slicing >>>print(a[1:3]) (40,60) Displaying items from 1st till 2nd. Concatenation >>> b=(2,4) >>>print(a+b) >>>(20,40,60,”apple”,”ball”,2,4) Adding tuple elements at the end of another tuple elements Repetition >>>print(b*2) >>>(2,4,2,4) repeating the tuple in n no of times Membership >>> a=(2,3,4,5,6,7,8,9,10) >>> 5 in a True >>> 100 in a False >>> 2 not in a False Returns True if element is present in tuple. Otherwise returns false. Comparison >>> a=(2,3,4,5,6,7,8,9,10) >>>b=(2,3,4) >>> a==b False >>> a!=b True Returns True if all elements in both elements are same. Otherwise returns false Tuple methods: ❖ Tuple is immutable so changes cannot be done on the elements of a tuple once it is assigned. methods example description a.index(tuple) >>> a=(1,2,3,4,5) >>> a.index(5) 4 Returns the index of the first matched item. a.count(tuple) >>>a=(1,2,3,4,5) >>> a.count(3) 1 Returns the count of the given element.
  • 3. Tuple Assignment: >>>(a,b,c)=(1,2,3) >>>print(a) 1 >>>print(b) 2 >>>print(c) 3 Tuple as return value: len(tuple) >>> len(a) 5 return the length of the tuple min(tuple) >>> min(a) 1 return the minimum element in a tuple max(tuple) >>> max(a) 5 return the maximum element in a tuple del(tuple) >>> del(a) Delete the entire tuple. ❖ Tuple assignment allows, variables on the left of an assignment operator and values of tuple on the right of the assignment operator. ❖ Multiple assignment works by creating a tuple of expressions from the right hand side, and a tuple of targets from the left, and then matching each expression to a target. ❖ Because multiple assignments use tuples to work, it is often termed tuple assignment. Uses of Tuple assignment: ❖ It is often useful to swap the values of two variables. Example: Swapping using temporary variable: Swapping using tuple assignment: a=20 b=50 temp = a a = b b = temp print("value after swapping is",a,b) a=20 b=50 (a,b)=(b,a) print("value after swapping is",a,b) Multiple assignments: Multiple values can be assigned to multiple variables using tuple assignment. ❖ A Tuple is a comma separated sequence of items. ❖ It is created with or without ( ).
  • 4. Dictionaries: ❖ A function can return one value. if you want to return more than one value from a function. we can use tuple as return value. Example1: Output: def div(a,b): r=a%b q=a//b return(r,q) a=eval(input("enter a value:")) b=eval(input("enter b value:")) r,q=div(a,b) print("reminder:",r) print("quotient:",q) enter a value:4 enter b value:3 reminder: 1 quotient: 1 Example2: Output: def min_max(a): small=min(a) big=max(a) return(small,big) a=[1,2,3,4,6] small,big=min_max(a) print("smallest:",small) print("biggest:",big) smallest: 1 biggest: 6 Tuple as argument: ❖ The parameter name that begins with * gathers argument into a tuple. Example: Output: def printall(*args): print(args) printall(2,3,'a') (2, 3, 'a') ❖ Dictionary is an unordered collection of elements. An element in dictionary has a key: value pair. ❖ All elements in dictionary are placed inside the curly braces i.e. { } ❖ Elements in Dictionaries are accessed via keys and not by their position. ❖ The values of a dictionary can be any data type. ❖ Keys must be immutable data type (numbers, strings, tuple) Operations on dictionary: 1. Accessing an element 2. Update
  • 5. Methods in dictionary: 3. Add element 4. Membership Operations Example Description Creating a dictionary >>> a={1:"one",2:"two"} >>> print(a) {1: 'one', 2: 'two'} Creating the dictionary with elements of different data types. accessing an element >>> a[1] 'one' >>> a[0] KeyError: 0 Accessing the elements by using keys. Update >>> a[1]="ONE" >>> print(a) {1: 'ONE', 2: 'two'} Assigning a new value to key. It replaces the old value by new value. add element >>> a[3]="three" >>> print(a) {1: 'ONE', 2: 'two', 3: 'three'} Add new element in to the dictionary with key. membership a={1: 'ONE', 2: 'two', 3: 'three'} >>> 1 in a True >>> 3 not in a False Returns True if the key is present in dictionary. Otherwise returns false. Method Example Description a.copy( ) a={1: 'ONE', 2: 'two', 3: 'three'} >>> b=a.copy() >>> print(b) {1: 'ONE', 2: 'two', 3: 'three'} It returns copy of the dictionary. here copy of dictionary ’a’ get stored in to dictionary ‘b’ a.items() >>> a.items() dict_items([(1, 'ONE'), (2, 'two'), (3, 'three')]) Return a new view of the dictionary's items. It displays a list of dictionary’s (key, value) tuple pairs. a.keys() >>> a.keys() dict_keys([1, 2, 3]) It displays list of keys in a dictionary a.values() >>> a.values() dict_values(['ONE', 'two', 'three']) It displays list of values in dictionary
  • 6. a.pop(key) >>> a.pop(3) 'three' >>> print(a) {1: 'ONE', 2: 'two'} Remove the element with key and return its value from the dictionary. setdefault(key,value) >>> a.setdefault(3,"three") 'three' >>> print(a) {1: 'ONE', 2: 'two', 3: 'three'} >>> a.setdefault(2) 'two' If key is in the dictionary, return its value. If key is not present, insert key with a value of dictionary and return dictionary. a.update(dictionary) >>> b={4:"four"} >>> a.update(b) >>> print(a) {1: 'ONE', 2: 'two', 3: 'three', 4: 'four'} It will add the dictionary with the existing dictionary fromkeys() >>> key={"apple","ball"} >>> value="for kids" >>> d=dict.fromkeys(key,value) >>> print(d) {'apple': 'for kids', 'ball': 'for kids'} It creates a dictionary from key and values. len(a) a={1: 'ONE', 2: 'two', 3: 'three'} >>>lena(a) 3 It returns the length of the list. clear() a={1: 'ONE', 2: 'two', 3: 'three'} >>>a.clear() >>>print(a) >>>{ } Remove all elements form the dictionary. del(a) a={1: 'ONE', 2: 'two', 3: 'three'} >>> del(a) It will delete the entire dictionary. Aliasing(copying)in Dictionary: ❖ Creating a copy of a dictionary is called aliasing. When you create a copy, both dictionary will be having same memory location. ❖ Changes in one dictionary will affect another dictionary. ❖ Aliasing refers to having different names for same dictionary values.
  • 7. ❖ In this a single dictionary object is created and modified using the subscript operator. ❖ When the first element of the dictionary named “a” is replaced, the first element of the dictionary named “b” is also replaced. ❖ This type of change is what is known as a side effect. This happens because after the assignment b=a, the variables a and b refer to the exact same dictionary object. ❖ They are aliases for the same object. This phenomenon is known as aliasing. ❖ To prevent aliasing, a new object can be created and the contents of the original can be copied which is called cloning. Cloning: ❖ To avoid the disadvantages of copying we are using cloning. ❖ Creating a copy of a same dictionary of elements with two different memory locations is called cloning. ❖ Changes in one dictionary will not affect locations of another dictionary. ❖ Cloning is a process of making a copy of the dictionary without modifying the
  • 8. original dictionary. ❖ In dictionary we can use copy() method for cloning. ❖ Slicing is not supported in the dictionary to reduce aliasing effect. Difference between List, Tuples and dictionary: List Tuples Dictionary A list is mutable A tuple is immutable A dictionary is mutable Lists are dynamic Tuples are fixed size in nature In values can be of any data type and can repeat, keys must be of immutable type List are enclosed in brackets[ ] and their elements and size can be changed Tuples are enclosed in parenthesis ( ) and cannot be updated Tuples are enclosed in curly braces { } and consist of key:value Homogenous Heterogeneous Homogenous Example: List = [10, 12, 15] Example: Words = ("spam", "egss") Or Words = "spam", "eggs" Example: Dict = {"ram": 26, "abi": 24} Access: print(list[0]) Access: print(words[0]) Access: print(dict["ram"])
  • 9. Can contain duplicate elements Can contain duplicate elements. Faster compared to lists Cant contain duplicate keys, but can contain duplicate values Slicing can be done Slicing can be done Slicing can't be done Usage: ❖ List is used if a collection of data that doesnt need random access. ❖ List is used when data can be modified frequently Usage: ❖ Tuple can be used when data cannot be changed. ❖ A tuple is used in combination with a dictionary i.e.a tuple might represent a key. Usage: ❖ Dictionary is used when a logical association between key:value pair. ❖ When in need of fast lookup for data, based on a custom key. ❖ Dictionary is used when data is being constantly modified.