0% found this document useful (0 votes)
14 views28 pages

Python Lists, Sets, Tuples, Dictionaries

Uploaded by

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

Python Lists, Sets, Tuples, Dictionaries

Uploaded by

venkat.2081518
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

MODULE-4

LIST SET, DICTIONARY AND TUPLE


List: Creating a List, List indexing and splitting, Python List Operations, List Built-in functions,
Tuple: Creating a tuple, Indexing, Deleting Tuple, Tuple operations, Tuple inbuilt functions.
Set: Creating a set, Python Set Operations, Python Built-in set methods.
Dictionary: Creating the dictionary, Properties of Keys and Values, Accessing the dictionary values,
and adding dictionary values, Iterating Dictionary, Built in Dictionary functions.
Lists

• Alistcanbedefinedasacollectionofvaluesoritemsofsameordifferenttypes.

• Theitemsinthelistareseparatedwiththecomma(,)andenclosedwiththe squarebrackets[].

• Alistisavaluethatcontainsmultiple valuesinanorderedsequence.

• Alistismutable(new,deleted,modify).

• Thevaluesinlistare calledelementsorsometimesitems.

• Thevalue[]isanemptylistthatcontains no values, similarto'',theemptystring.

• Items in the lists can be of different data types.


Eg:a=[10,20,30,40];b=[10,20,“abc”,4.5]
['spam',2.0,5,[10,20]]
A list within another list is nested. A list that contains no elements is called an empty list; you can create one
with empty brackets, [].

Creating a List

 Alistcanbedefinedasfollows.

L1 = ["Raju", 102, "India"] #Createslist['Raju',102,'India']

L2 = [1, 2, 3, 4, 5, 6] #Creates List [1, 2, 3, 4, 5, 6]


L3 = [ ] #CreatesListL3withnoitems spam = ['cat', 'bat',
'rat', 'elephant']

 Alistcanbedisplayedasfollows.

print(L1) #displays['Raju',102,'India']

print(L2) #displays[1,2, 3,4, 5,6]

As you might expect, you can assign list values to variables:


>>>cheeses=['Cheddar','Edam','Gouda']
>>>numbers=[17,123]
>>>empty=[]
>>>print cheeses, numbers, empty ['Cheddar',
'Edam','Gouda'] [17, 123] []

Listindexingandsplitting

• Toaccessvaluesinlists,usethesquarebracketsforslicingalongwiththeindex orindicesto obtain


value available at that index.
• Theintegerinsidethesquarebracketsthatfollowsthe listis calledanindex.

• Thefirstvalueinthelistisatindex 0,thesecondvalueisatindex 1,thethirdvalueisatindex 2, and so on.


>>>spam=['cat', 'bat','rat','elephant']

>>>spam #['cat','bat','rat','elephant']

>>>spam[0] #'cat'

>>>spam[1] #'bat'

>>>spam[2] #'rat'

>>>spam[3] #'elephant‘

>>>spam[1.0] #TypeError:listindices mustbeintegers

>>>spam[int(1.0)] #’bat’

>>>spam[4] #IndexError:listindexoutofrange

>>>'Hello'+spam[2] #'Hellorat‘

>>>'The '+spam[0]+'ate'+spam[2] #'Thecat ate rat'


• Listscanalso containotherlist [Link] inthese listsoflistscanbeaccessedusing
multiple indexes.
• Thefirst indexdictateswhichlist valuetouse,andthesecondindicatesthevaluewithinthelist value.
>>>spam=[['cat','bat'], [10,20,30,40,50]]

>>>spam #[['cat','bat'],[10,20,30,40,50]]

>>>spam[0][1] #'bat'

>>>spam[1][4] #50

>>>spam[2][0] #IndexError:listindex outofrange

>>>spam[1][5] #IndexError

Negative Indexes

• Indexesstartat0andgoup,wecanalsousenegativeintegersfortheindex.
• Theintegervalue-1referstothelastindexinalist,thevalue -2referstothesecond-to-last indexin a list, and
so on.
>>>spam=['cat','bat','rat','elephant']

>>>spam[-1] #'elephant'

>>>spam[-3] #'bat'

>>>spam[3] #elephant

• Indexesstart at0andgoup,wecanalsousenegative integersfortheindex.

• Theintegervalue-1referstothelastindex inalist,thevalue-2referstothe second-


to-last index in a list, and so on.
>>>spam=['cat','bat','rat','elephant']

>>>spam[-1] #'elephant'

>>>spam[-3] #'bat'

>>>'The '+spam[-1]+'isafraid ofthe'+spam[-3] +'.‘

#'Theelephant isafraidofthebat.'

Getting Sublists with Slices

• Anindexcangetasingle valuefromalist, Aslicecanget severalvalues fromalist intheformofa new list.


• Asliceistypedbetweensquarebracketslikeanindexbutithas2integersseparatedbyacolon.

• Thedifferencebetweenindexesandslices.

o spam[2]isalistwithanindex(oneinteger).

o spam[1:4]isalistwithaslice(twointegers).

o Inaslice,thefirstinteger istheindexwheretheslicestarts(including)andsecondintegeris the


index where the slice ends (Excluding) and evaluates to a new list value

>>>spam=['cat','bat','rat','elephant']

>>>spam[0:4] #['cat','bat','rat','elephant']

>>>spam[1:3] #['bat','rat']

>>>spam[0:-1] #['cat','bat', 'rat']

>>>spam[::-1] #['elephant','rat','bat','cat']

 Wecan leaveout oneorboth of theindexes on either side ofthecolon in theslice.


 Leavingoutthefirst indexisthesameasusing0and Leavingoutthesecond indexissameas using the
length of the list.
>>>spam=['cat','bat','rat','elephant']

>>>spam[:2] #['cat','bat']printselementsofpos0and1

>>>spam[1:] #['bat','rat','elephant']printsallexcluding0

>>>spam[:] #['cat','bat','rat','elephant']printsall

GettingaList’sLengthwith len()

 Thelen() functionwillreturnthenumberofvaluesthat areinalist valuepassedtoit,just likeit can


count the number of characters in a string value.
>>>spam=['cat','bat','rat','elephant']

>>>len(spam)
ChangingValuesin aList withIndexes

 Whenthebracketoperatorappearsontheleft sideofanassignment,itidentifiestheelement of the list


that will be assigned.
>>>spam=['cat','bat','rat','elephant']

>>>spam[1]='aardvark‘ #pos1batvalueischangedtoaardvark

>>>spam #['cat','aardvark','rat','elephant']

>>>spam[2]=spam[1] #pos1 valueisassignedtopos2

>>>spam #['cat','aardvark','aardvark','elephant']

>>>spam[-1]=12345 #lastposvaueischangedto12345

>>>spam #['cat','aardvark','aardvark',12345]

 The+operatorcancombinetwo liststocreateanewlist value inthesamewayit combinestwo strings


into a new string value.
 The*operatorcanalsobeusedwithalistandanintegervaluetoreplicatethelist.

>>>[1,2,3]+['A','B','C'] #[1,2,3,'A', 'B','C']

>>>['X', 'Y', 'Z'] *3 #['X','Y','Z','X','Y','Z','X','Y','Z']

>>>spam = [1, 2, 3]

>>>spam=spam+['A', 'B','C']

>>>spam #[1,2,3,'A','B','C']
 Thedelstatement willdeletevaluesatanindexinalist.

 Allofthe values inthe listafterthedeletedvaluewillbemovedup oneindex.

>>>spam=['cat','bat','rat','elephant']

>>>delspam[2] #deleteselementatpos2

>>>spam #['cat','bat','elephant']

>>>delspam[2] #deleteselementatpos2

>>>spam #['cat', 'bat']

Python list Operations:


1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison
createalist >>>a=[2,3,4,5,6,7,8,9,10 in
] thiswaywecancreatealis
>>>print(a) tatcompile time
[2,3,4,5, 6, 7,8,9, 10]
Indexing >>>print(a[0]) Accessingtheiteminthe
2 position0
>>>print(a[8]) Accessingtheiteminthe
10 position8
>>>print(a[-1]) Accessinga

lastelement
10 usingnegativeindexing.

>>>print(a[0:3])
[2,3,4] Printingapartofthelist.
Slicing
>>>print(a[0:])
[2,3,4,5, 6, 7,8,9, 10]
>>>b=[20,30] Addingandprintingthe
Concatenation >>>print(a+b) items of two lists.

[2,3,4,5,6, 7,8,9,10, 20,30]


>>>print(b*3) Createamultiplecopiesofth
Repetition [20,30,20,30,20,30] esamelist.

>>>print(a[2]) Updatingthelistusing
4 indexvalue.
Updating >>> a[2]=100
>>>print(a)
[2,3,100, 5, 6, 7,8,9, 10]
Membership a=[2,3,4,5,6,7,8,9,10] ReturnsTrueifelementispr
>>>5 ina [Link]
True nsfalse.
>>>100ina
False
>>>2notina
False
a=[2,3,4,5,6,7,8,9,10] ReturnsTrueifallelementsi
Comparison
>>>b=[2,3,4] nbothelementsaresame.
>>>a==b Otherwisereturnsfalse
False
>>>a!=b
True

List Built-in functions /methods:


Pythonprovidesmethodsthat operateonlists.

Syntax:[Link](element/index/list)

Syntax Example Description


>>>a=[1,2,3,4,5]
>>> [Link](6) Addanelementto the end of
[Link](element)
>>> print(a) the list
[1,2,3,4,5,6]
[Link](index,element) >>>[Link](0,0) Insertanitematthe defined
>>>print(a) index
[0,1,2, 3,4, 5, 6]
[Link](b) >>>a=[1,2,3,4,5] Addallelementsofa list to the
>>>b=[7,8,9] another list
>>> [Link](b)
>>> print(a)
[0,1,2, 3, 4, 5,6,7,8,9]
>>>a=[0,1,2,3,8,5,6,7, 8,9] Returnstheindexof the first
[Link](element)
>>>[Link](8) matched item
4
>>>a=[1,2,3,4,5]
Sortitemsinalistin ascending
>>>sum(a)
sum()
order
>>>print(a)
[0,1,2, 3, 4, 5,6,7,8,9]
>>> [Link]()
Reversetheorderof items in
[Link]() >>>print(a)
the list
[8,7,6, 5, 4, 3,2,1,0]

[Link]() >>>[Link]() Removes and


0 returnsan element
>>>print(a) atthelastelement
=[8,7,6,5, 4,3,2, 1]

[Link](index) >>> [Link](0) Removethe


8 particularelement
>>>print(a) andreturn it.
[7,6,5, 4,3, 2,1,0]

>>>a=[7,6,5,4, 3,2, 1]
[Link](element) >>>[Link](1) Removesanitem
>>>print(a) fromthelist
[7,6, 5,4,3, 2]
[Link](element) >>>a=[7,6, 5,4, 3, 2,6] Returnsthecountof
>>>[Link](6) numberofitems
2 passedasan
argument

>>>a=[7,6, 5,4, 3,2]


Returnsa
>>> b=[Link]()
[Link]() >>>print(b) copyofthelist
[7,6, 5,4,3, 2]
>>>a=[7,6, 5,4, 3,2]
len(list) >>>len(a) Returnthelengthof
6 thelength
>>>a=[7,6,5,4,3,2]
sum(list) >>>sum(a) Returnthesumofelementinalis
27 t
[Link]() >>> [Link]() Removesallitems from the list.
>>>print(a)
[]
del(a) >>>del(a) deletethe entirelist.
>>>print(a)
Error:name'a'isnot defined

List loops:
1. Forloop

2. Whileloop

3. Infiniteloop

List using For Loop:


The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects.
Iterating over a sequence is called traversal.
Loop continues until we reach the last item in the sequence.
The body of for loop is separated from the rest of the code using indentation.

Syntax:
forvalinsequence:
Accessingelement output
a=[10,20,30,40,50] 10
foriin a: 20
print(i) 30
40
50
Accessingindex output
a=[10,20,30,40,50] 0
fori in range(0,len(a),1): 1
print(i) 2
3
4
Accessingelementusingrange: output
a=[10,20,30,40,50] 10
foriin range(0,len(a),1): 20
print(a[i]) 30
40
50

List using While loop

The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is [Link] the condition is tested and the result is false, the loop body will be
skipped and the first statement after the while loop will be executed.

Syntax:
while (condition): body of while
Sum of elements in list Output:15
a=[1,2,3,4,5]
i=0 sum=0
while i<len(a): sum=sum+a[i] i=i+1
print(sum)
Mutability:
Lists are mutable. (can be changed)
Mutability is the ability for certain types of data to be changed without entirely
recreating it.
An item can be changed in a list by accessing it directly as part of the assignment
statement.
Using the indexing operator (square brackets[ ]) on the left side of an assignment, one of
the list items can be updated.

Example description

changing single element


>>> a=[1,2,3,4,5]
>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
>>> a=[1,2,3,4,5] changing multiple element
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
>>> a=[1,2,3,4,5] The elements from a list can also be
>>> a[0:3]=[ ] removed by assigning the empty list to
>>> print(a) them.
[4, 5]
>>> a=[1,2,3,4,5] The elements can be inserted into a list by
>>> a[0:0]=[20,30,45] squeezing them into an empty slice at the
>>> print(a) desired location.
[20,30,45,1, 2, 3, 4, 5]

Aliasing:
Creating a copy of a list is called aliasing.
When you create a copy both the list will be having same memory location.
changes in one list will affect another list.
Alaising refers to having different names for same list values.

Example Output:
a= [1, 2, 3 ,4 ,5]
b=a
print (b) [1, 2, 3, 4, 5]
a is b True
a[0]=100
print(a) [100,2,3,4,5]
print(b) [100,2,3,4,5]
Clonning:
To avoid the disadvantages of copying we are using cloning.
Creating a copy of a same list of elements with two different memory locations is called

cloning.
Changes in one list will not affect locations of aother list.
Cloning is a process of making a copy of the list without modifying the original
list.
Slicing
list()method
copy() method
clonning using Slicing
>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b) [1,2,3,4,5]
>>>a is b
False #because they have different memory location
clonning using List( ) method
>>>a=[1,2,3,4,5]
>>>b=list
>>>print(b) [1,2,3,4,5]
>>>a is b false
>>>a[0]=100
>>>print(a)
>>>a=[100,2,3,4,5]
>>>print(b)
>>>b=[1,2,3,4,5]
clonning using copy() method

a=[1,2,3,4,5]
>>>b=[Link]()
>>> print(b) [1, 2, 3, 4, 5]
>>> a is b False
Tuple:
 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) it convert the given tuple
>>> a=list(a) into list.
>>> print(a)
[1, 2, 3, 4, 5]
tuple( ) >>> a=[1,2,3,4,5] it convert the given list into
>>> a=tuple(a) tuple.
>>> print(a)
(1, 2, 3, 4, 5)

Creating a Tuple
Creating the tuple with
>>>a=(20,40,60,”apple”,”ball”) elementsofdifferent data

types.

Indexing:
>>>print(a[0]) 20 Accessingtheiteminthe position 0
>>>a[2] Accessingtheiteminthe
60 position2

Deleting a Tuple:
del(tuple) >>>del(a) Deletetheentiretuple.
Tuple operations:
 Indexing
 Slicing
 Concatenation
 Repetitions
 Membership
 Comparison
Operations examples description
Creating the tuple with
Creating a tuple >>>a=(20,40,60,”apple”,”ball”) elements of different data
types.
>>>print(a[0]) Accessing the item in the
Indexing 20 position 0
>>> a[2] Accessing the item in the
60 position 2
Slicing >>>print(a[1:3]) Displaying items from 1st
(40,60) till 2nd.
Concatenation >>> b=(2,4) Adding tuple elements at
>>>print(a+b) the end of another tuple
>>>(20,40,60,”apple”,”ball”,2,4) elements
Repetition >>>print(b*2) repeating the tuple in n no
>>>(2,4,2,4) of times
>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in tuple. Otherwise
False returns false.
>>> 2 not in a
False
>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4) Returns True if all elements
Comparison
>>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True

Tuple methods:

Tuple inbuilt functions


methods example description
[Link](tuple) >>> a=(1,2,3,4,5) Returns the index of the
>>> [Link](5) first matched item.
4
[Link](tuple) >>>a=(1,2,3,4,5) Returns the count of the
>>> [Link](3) given element.
1
len(tuple) >>> len(a) return the length of the
5 tuple
min(tuple) >>> min(a) return the minimum
1 element in a tuple
max(tuple) >>> max(a) return the maximum
5 element in a tuple
del(tuple) >>> del(a) Delete the entire tuple.

Tuple Assignment:
 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.
Swapping using temporary variable: Swapping using tuple assignment:
a=20 a=20
b=50 b=50
temp = a (a,b)=(b,a)
a=b print("value after swapping is",a,b)
b = temp
print("value after swapping is",a,b)

Multipleassignments:
Multiplevaluescanbeassignedtomultiplevariablesusingtuple assignment.
>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3
Tuple as return value:
 
A Tuple is a comma separated sequence of items.
 
It is created with or without ( ).
 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): enter a value:4
r=a%b enter b value:3
q=a//b reminder: 1
return(r,q) quotient: 1
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
Example2: Output:
def min_max(a): smallest: 1
small=min(a) biggest: 6
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)

Tupleasargument:
Theparameternamethatbeginswith *gathersargumentintoatuple.
Example: Output:
def printall(*args): (2, 3, 'a')
print(ar
gs)
printall(2,
3,'a')
Set: Creating a set, Python Set Operations, Python Built-in set methods.
Dictionary: Creating the dictionary, Properties of Keys and Values, Accessing the
dictionary values, and adding dictionary values, Iterating Dictionary, Built in Dictionary
functions.

Set Introduction
Sets in Python are an unordered collection of unique, immutable elements. They are
mutable themselves, meaning elements can be added or removed after creation, but the
individual elements within a set must be immutable (e.g., numbers, strings, tuples). Sets
are particularly useful for operations that involve uniqueness, membership testing, and
mathematical set operations.

Key Characteristics of Python Sets

 Unordered:

Elements in a set do not maintain a specific order and cannot be accessed by index.

 Unique Elements:

Sets automatically handle duplicate values; if you try to add an existing element, it will
not be added again.

 Mutable:

You can add or remove elements from a set after it's created.

 Immutable Elements:
While the set itself is mutable, the individual elements stored within it must be of an
immutable data type.

Creating a set
Sets can be created using curly braces {} or the set() constructor.
# Using curly braces
my_set = {1, 2, 3, 4, 5}
print(my_set)
# Using the set() constructor with an iterable (e.g., a list)
another_set = set([1, 2, 2, 3, 4])
print(another_set) # Output will be {1, 2, 3, 4} due to uniqueness

Python Set Operations

 Adding Elements:
 add(element): Adds a single element to the set.

 update(iterable): Adds all elements from an iterable to the set.

 Removing Elements:
 remove(element): Removes a specified element. Raises a KeyError if the element is
not found.

 discard(element): Removes a specified element if it exists; does nothing if not found.

 pop(): Removes and returns an arbitrary element.

 clear(): Removes all elements from the set.

 Set Mathematics:
 union() or |: Returns a new set containing all unique elements from both sets.

 intersection() or &: Returns a new set containing common elements from both sets.

 difference() or -: Returns a new set containing elements present in the first set but not
in the second.

 symmetric_difference() or ^: Returns a new set containing elements present in either


set, but not in both.

 Membership Testing:
 in keyword: Checks if an element is present in the set.

set_a = {1, 2, 3}
set_b = {3, 4, 5}
# Add an element
set_a.add(6)
print(f"Set A after adding 6: {set_a}")

# Union
union_set = set_a.union(set_b)
print(f"Union of A and B: {union_set}")

# Intersection
intersection_set = set_a.intersection(set_b)
print(f"Intersection of A and B: {intersection_set}")

# Membership test
print(f"Is 2 in set_a? {2 in set_a}")

Python Built-in set methods

Python's built-in set type provides various methods for manipulating and performing
operations on sets. These methods can be broadly categorized as follows:

1. Adding Elements:

 add(element): Adds a single element to the set. If the element is already present, the
set remains unchanged.

 update(iterable): Adds all elements from an iterable (like another set, list, or tuple) to
the set. Duplicate elements are ignored.

2. Removing Elements:

 remove(element): Removes the specified element from the set. Raises a KeyError if
the element is not found.

 discard(element): Removes the specified element from the set. Does nothing if the
element is not found (no error is raised).
 pop(): Removes and returns an arbitrary element from the set. Raises a KeyError if the
set is empty.

 clear(): Removes all elements from the set, making it empty.

3. Set Operations:

 union(other_set) or set1 | set2: Returns a new set containing all unique elements from
both sets.

 intersection(other_set) or set1 & set2: Returns a new set containing only the
common elements between the sets.

 difference(other_set) or set1 - set2: Returns a new set containing elements present in


the first set but not in the second.

 symmetric_difference(other_set) or set1 ^ set2: Returns a new set containing


elements that are in either of the sets, but not in both.

4. Set Comparison and Information:

 issubset(other_set) or set1 <= set2: Returns True if all elements of the first set are
present in the second set.

 issuperset(other_set) or set1 >= set2: Returns True if all elements of the second set
are present in the first set.

 isdisjoint(other_set): Returns True if the two sets have no common elements.

 copy(): Returns a shallow copy of the set.

5. In-place Set Operations (Modifying the original set):

 intersection_update(other_set) or set1 &= set2: Updates the set to contain only the
common elements with another set.

 difference_update(other_set) or set1 -= set2: Updates the set by removing elements


present in another set.

 symmetric_difference_update(other_set) or set1 ^= set2: Updates the set to contain


only the symmetric difference with another set.
my_set = {1, 2, 3}
other_set = {3, 4, 5}

my_set.add(4) # my_set is now {1, 2, 3, 4}


my_set.update([5, 6]) # my_set is now {1, 2, 3, 4, 5, 6}

union_set = my_set.union(other_set) # union_set is {1, 2, 3, 4, 5, 6}


intersection_set = my_set.intersection(other_set) # intersection_set is {3, 4, 5}

my_set.remove(1) # my_set is now {2, 3, 4, 5, 6}


my_set.discard(7) # my_set remains {2, 3, 4, 5, 6} (no error)

Dictionary Introduction
A Python dictionary is a built-in data structure that stores data in key-value pairs. It is a
collection that is ordered (as of Python 3.7+), changeable, and does not allow duplicate
keys.

Key Characteristics:

 Key-Value Pairs:

Each item in a dictionary consists of a unique key mapped to a corresponding value.

 Ordered (Python 3.7+):

The order of key-value pairs in a dictionary is preserved according to their insertion


order.

 Changeable (Mutable):

Dictionaries can be modified after creation; elements can be added, removed, or


updated.

 No Duplicate Keys:

Each key within a dictionary must be unique. If a duplicate key is assigned, it will
overwrite the previous value associated with that key.

 Keys Must Be Immutable:


Dictionary keys must be of an immutable data type, such as strings, numbers (integers,
floats), or tuples. Mutable types like lists or other dictionaries cannot be used as keys.

 Values Can Be Any Type:


Dictionary values can be of any data type, including other dictionaries, lists, functions,
or any standard Python object.

Creating the dictionary


Dictionaries are created using curly braces {} with key-value pairs separated by
colons : and individual pairs separated by commas ,.

# Example of creating a dictionary


my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}

Properties of Keys and Values


In Python dictionaries, both keys and values possess distinct properties:

Properties of Keys:

 Immutability:

Dictionary keys must be immutable objects. This means they cannot be changed after
creation. Examples of immutable types suitable for keys include strings, numbers
(integers, floats), and tuples. Mutable types like lists or other dictionaries cannot be
used as keys.

 Uniqueness:

Each key within a single dictionary must be unique. Duplicate keys are not allowed; if a
key is assigned a new value, the previous value associated with that key will be
overwritten.

 Hashability:
Keys must be hashable, meaning they must have a hash value that can be used for
efficient lookup. Immutable types are generally hashable.

 Case Sensitivity:
Keys are case-sensitive. For example, 'Key' and 'key' are treated as distinct keys.

Properties of Values:

 Mutability:

Dictionary values can be of any data type, including mutable types like lists, other
dictionaries, or custom objects. They can be changed or updated after the dictionary is
created.

 Duplication Allowed:

Unlike keys, values in a dictionary can be duplicated. Multiple keys can point to the
same value.

 No Hashability Requirement:

Values do not need to be hashable.

 Accessibility:
Values are accessed using their corresponding keys. You cannot directly access a key
using its value.

Accessing the dictionary values

Values are accessed using their corresponding keys, either by enclosing the key in
square brackets [] or by using the get() method.

# Accessing values
print(my_dict["name"]) # Output: Alice
print(my_dict.get("age")) # Output: 30

Adding dictionary values

Elements can be added, updated, or removed using various methods.


# Adding a new key-value pair
my_dict["occupation"] = "Engineer"

# Updating an existing value


my_dict["age"] = 31

# Removing a key-value pair


del my_dict["city"]

Iterating Dictionary

In Python, dictionaries can be iterated in several ways to access their keys, values, or
both.

1. Iterating over Keys (Default Behavior):

When a dictionary is directly used in a for loop, it iterates over its keys.

my_dict = {"name": "Alice", "age": 30, "city": "New York"}


for key in my_dict:
print(key)

2. Iterating over Values:

The values() method returns a view object that displays a list of all the values in the
dictionary.

my_dict = {"name": "Alice", "age": 30, "city": "New York"}


for value in my_dict.values():
print(value)

3. Iterating over Key-Value Pairs:


The items() method returns a view object that displays a list of a dictionary's key-value
tuple pairs. This is often the most convenient way to access both keys and values
simultaneously.

my_dict = {"name": "Alice", "age": 30, "city": "New York"}


for key, value in my_dict.items():
print(f"{key}: {value}")

4. Iterating with keys() method:

The keys() method returns a view object that displays a list of all the keys in the
dictionary. While directly iterating over the dictionary also yields keys, keys() is
explicit.

my_dict = {"name": "Alice", "age": 30, "city": "New York"}


for key in my_dict.keys():
print(key)

Built in Dictionary functions

Python provides several built-in functions that can be used with dictionaries, as well as
a set of methods specific to dictionary objects.
 len(dictionary): Returns the number of key-value pairs (items) in the dictionary.

my_dict = {"a": 1, "b": 2, "c": 3}


print(len(my_dict))

 dict(): This is the dictionary constructor. It can be used to create an empty dictionary or
to create a dictionary from an iterable of key-value pairs (e.g., a list of tuples).

empty_dict = dict()
print(empty_dict)

from_list = dict([("x", 10), ("y", 20)])


print(from_list)

 sorted(dictionary): Returns a new sorted list of the dictionary's keys. The sorting
order is determined by the default comparison for the key types.

my_dict = {"c": 3, "a": 1, "b": 2}


sorted_keys = sorted(my_dict)
print(sorted_keys)

 all(dictionary): Returns True if all keys in the dictionary are truthy (evaluate to True),
or if the dictionary is empty. Returns False otherwise.

dict1 = {1: "one", 2: "two"}


print(all(dict1))

dict2 = {0: "zero", 1: "one"}


print(all(dict2))

 any(dictionary): Returns True if any key in the dictionary is truthy, or if the dictionary
is empty. Returns False if all keys are falsy.

dict1 = {0: "zero", 1: "one"}


print(any(dict1))

dict2 = {0: "zero", False: "false"}


print(any(dict2))

 min(dictionary): Returns the minimum key in the dictionary.

my_dict = {"c": 3, "a": 1, "b": 2}


print(min(my_dict))

 max(dictionary): Returns the maximum key in the dictionary.


my_dict = {"c": 3, "a": 1, "b": 2}
print(max(my_dict))

Note: While these built-in functions can interact with dictionaries, dictionaries also have
a rich set of methods (e.g., keys(), values(), items(), get(), pop(), update(), etc.) that are
specifically designed for dictionary manipulation and retrieval.

Sample Questions

1. Difference between List and Dictionary in Python with example program for each.

2. Difference between List and Tuple in Python with example program for each.

3. Convert list of tuple into dictionary using iterative method with example program.

4. Which is better list or tuple in Python? Justify your answer with example program?

5. Difference Between ‘+’ and ‘append’ in Python with example.

6. How to Split Elements of a List? Explain the different methods.

7. Give any two ways to create a list in Python and reverse a list.

8. Explain the different list methods in Python for Python lists and give example
program for any five.

9. What is Immutable in Tuples? Justify your answer with example program.

10. Explain the append() and extend() in Python with suitable program for each.

11. Given a list of lists, write a Python program to extract the last element of each
sublist in the given list of lists.

12. List out the Different Operations Related to Tuples. Explain any five with example
program for each.

13. Explain the different tuple methods in Python for Python tuples and give example
program for each.

14. Advantages of tuple over list with example.

15. List out the Different Operations Related to sets. Explain with example program.

16. Explain the different set methods in Python for Python tuples and give example
program for each.

17. Create a dictionary and explain the properties of keys and values.

18. Explain any 5 ways to iterate through a dictionary with suitable example for each.

19. Write a python program to removing dictionary from list of dictionaries with
output.

20. What are the built-in methods that you can use on dictionaries? Explain any five
with an example program.

You might also like