CSE114 Unit2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 74

UNIT 2

Lists and Nested List: Introduction, Accessing list, Operations, Working with lists,
Library Functions and Methods with Lists.
Tuple: Introduction, Accessing tuples, Operations, Working, Library Functions and
Methods with Tuples.
Dictionaries :Introduction, Accessing values in dictionaries, Working with dictionaries,
Library Functions

By Ms. Preeti Kaushik


LIST: Introduction
• List is just like an array
• List can be homogenous or heterogenous(A single list may contain DataTypes like
Integers, Strings, as well as Objects)
• Lists are mutable, and hence, they can be altered even after their creation.
• A List is an ordered Collection (sometimes called a sequence). This means that
a List maintains the order of the elements. In other words, the first element you add
remains at index 0. The second element you add remains at index 1.
• List in Python are ordered and have a definite count. The elements in a list are
indexed according to a definite sequence and the indexing of a list is done with 0
being the first index.
• Each element in the list has its definite place in the list, which allows duplicating of
elements in the list, with each element having its own distinct place and credibility.

• lists are written with square brackets. [ ]

By Ms. Preeti Kaushik


List creation
my_list = [] # empty list

my_list = [1, 2, 3] # list of integers

my_list = [1, "Hello", 3.4] # list with mixed datatypes

my_list = ["mouse", [8, 4, 6], ['a’]] # nested list

list3 = ["a", "b", "c", "d"]

By Ms. Preeti Kaushik


Getting list as input from the user
lst = [] # creating an empty list
n = int(input("Enter number of elements : ")) # number of elements as input
for i in range(0, n): # iterating till the range
ele = int(input())
lst.append(ele) # adding the element
print(lst)

By Ms. Preeti Kaushik


How to access list element?
• List elements can be accessed by
a) Index
b) Negative indexing
c) Using slice operator

By Ms. Preeti Kaushik


a) Index
• We can use the index operator [] to access an item in a list. Index starts from 0.
So, a list having 5 elements will have index from 0 to 4.

• Trying to access an element other that this will raise an IndexError.


IndexError: list index out of range

• The index must be an integer. We can't use float or other types, this will result
into TypeError.
TypeError: list indices must be integers or slices, not float

• Nested list are accessed using nested indexing.


By Ms. Preeti Kaushik
my_list = ['p','r','o','b','e']
print(my_list[0]) # Output: p
print(my_list[2]) # Output: o
print(my_list[4]) # Output: e
# my_list[4.0] # Error! Only integer can be used for indexing
n_list = ["Happy", [2,0,1,5]] # Nested List
# Nested indexing
print(n_list[0][1]) # Output: a
print(n_list[1][3]) # Output: 5

By Ms. Preeti Kaushik


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

Example 1:
my_list = ['p','r','o','b','e']
print(my_list[-1])
print(my_list[-5])

By Ms. Preeti Kaushik


c) Slice operator
• The slice operator [n:m] returns the part of the string from the n’th character to the m’th
character, including the first but excluding the last. In other words, start with the character
at index n and go up to but do not include the character at index m.

Example:
my_list = ['p','r','o','g','r','a','m','i','z']
print(my_list[2:5]) # elements 3rd to 5th
print(my_list[:-5]) # elements beginning to 4th
print(my_list[5:]) # elements 6th to end
print(my_list[:]) # elements beginning to end

By Ms. Preeti Kaushik


Find output?
Q1)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])

Q2)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])

Q3)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])

Q4)
s = "python rocks"
print(s[7:11] * 3)
By Ms. Preeti Kaushik
Q4)
# Python program to demonstrate accessing of element from list

# Creating a List with the use of multiple values


List = ["Geeks", "For", "Geeks"]

# accessing a element from the list using index number


print("Accessing a element from the list")
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List


List = [['Geeks', 'For'] , ['Geeks’]] # (By Nesting a list inside a List)

# accessing a element from the Multi-Dimensional List using index number


print("Acessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])

Q 5)
thislist = ["apple","banana","cherry","orange","kiwi","melon","mango"]
print(thislist[-4:-1])
print(thislist[-1:-4]) # cannot print in reverse order. Prints []
By Ms. Preeti Kaushik
Loop through list
You can loop through the list items by using a for loop:

Example:
#program to print list element one by one
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)

Output:
apple
banana
cherry

By Ms. Preeti Kaushik


Questions

1) Print all the even numbers elements from the list


2) Search given element
3) Find output
for fruit in ['apple','banana','mango']:
print("I like",fruit)

By Ms. Preeti Kaushik


How to change element?
List are mutable. Hence can be changed using = operator

Example:
odd = [2, 4, 6, 8]
odd[0] = 1 # change the 1st item
print(odd) # Output: [1, 4, 6, 8]
odd[1:4] = [3, 5, 7] # change 2nd to 4th items
print(odd) # Output: [1, 3, 5, 7]

By Ms. Preeti Kaushik


How to add elements to a list or join list?
• We can add one item to a list using append() and method or add several items
using extend() method.

Example:
odd = [1, 3, 5]
odd.append(7)
print(odd) # Output: [1, 3, 5, 7]
odd.extend([9, 11, 13])
print(odd) # Output: [1, 3, 5, 7, 9, 11, 13]

By Ms. Preeti Kaushik


• We can also use + operator to combine two lists. This is also called
concatenation.
• The * operator repeats a list for the given number of times.

Example:
odd = [1, 3, 5]
print(odd + [9, 7, 5]) # Output: [1, 3, 5, 9, 7, 5]
print(["re"] * 3) #Output: ["re", "re", "re"]

By Ms. Preeti Kaushik


• Furthermore, we can insert one item at a desired location by using the method
insert() or insert multiple items by squeezing it into an empty slice of a list.

Example 1:
odd = [1, 9]
odd.insert(1,3)
print(odd) # Output: [1, 3, 9]
odd[2:2] = [5, 7]
print(odd) # Output: [1, 3, 5, 7, 9]

Example 2:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
Output: ['apple', 'orange', 'banana', 'cherry']
By Ms. Preeti Kaushik
#Adding list one by one element using append
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

for x in list2:
list1.append(x)

print(list1)

By Ms. Preeti Kaushik


Remove or delete element
1) Using del keyword
2) Using remove() method
3) Using pop() method
4) Using clear() method

By Ms. Preeti Kaushik


1) Del keyword
• We can delete one or more items from a list using the keyword del. It can even delete the
list entirely.

Example:
my_list = ['p','r','o','b','l','e','m']
del my_list[2] # delete one item
print(my_list) # Output: ['p', 'r', 'b', 'l', 'e', 'm']
del my_list[1:5] # delete multiple items
print(my_list) # Output: ['p', 'm']
del my_list # delete entire list
print(my_list) # Error: List not defined

By Ms. Preeti Kaushik


2) remove()
• We can use remove() method to remove the given item

Example:
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
print(my_list) # Output: ['r', 'o', 'b', 'l', 'e', 'm’]

output
['r', 'o', 'b', 'l', 'e', 'm']

By Ms. Preeti Kaushik


3) pop()
• The pop() method removes and returns the last item if index is not
provided. This helps us implement lists as stacks (first in, last out data
structure).

Example:
my_list = ['p','r','o','b','l','e','m'] output
['p', 'r', 'o', 'b', 'l', 'e', 'm']
r
print(my_list) ['p', 'o', 'b', 'l', 'e', 'm']
print(my_list.pop(1)) m
print(my_list)
print(my_list.pop())

By Ms. Preeti Kaushik


4) clear()
• empty a list.

Example:
my_list = ['p','r','o','b','l','e','m']
print(my_list)
my_list.clear()
print(my_list)

output
['p', 'r', 'o', 'b', 'l', 'e', 'm']
[]

By Ms. Preeti Kaushik


• Finally, we can also delete items in a list by assigning an empty list to a slice of
elements.

Example:
my_list = ['p','r','o','b','l','e','m']
my_list[2:3] = []
print(my_list)
my_list[2:5] = []
Print(my_list)

Output:
['p', 'r', 'b', 'l', 'e', 'm’]
['p', 'r', 'm’]
By Ms. Preeti Kaushik
Copy a list
• You cannot copy a list simply by typing list2 = list1, because: list2 will only be a
reference to list1, and changes made in list1 will automatically also be made in list2.
• We can copy using built in method a) copy() b) list()

Example Using copy():


thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)

Example using list():


thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)

By Ms. Preeti Kaushik


Check if Item Exists/ membership
• To determine if a specified item is present in a list use the in /not in keyword:
Example:
my_list = ['p','r','o','b','l','e','m']
print('p' in my_list)
print('a' in my_list)
print('c' not in my_list)

• List length
use the len() function:
Example:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))

Output
3
By Ms. Preeti Kaushik
Find output?
1) thislist = ["apple","banana","cherry"]
mylist=thislist
thislist[1]="abc"
print(thislist)
print(mylist)

2)
List = ['G','E','E','K','S','F','O','R','G','E','E','K','S']
print(List[::-1])

3)
thislist = ["apple","banana","cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
By Ms. Preeti Kaushik
Python List Methods
append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of number of items passed as an argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list

By Ms. Preeti Kaushik


my_list = [3, 8, 1, 6, 0, 8, 4]
print(my_list.index(8))
print(my_list.count(8))
my_list.sort()
print(my_list)
my_list.reverse()
print(my_list)

By Ms. Preeti Kaushik


Built-in functions with List
FUNCTION DESCRIPTION
apply a particular function passed in its argument to all of the list elements stores the intermediate
reduce()
result and only returns the final summation value
sum() Sums up the numbers in the list
ord() returns the number representing the unicode code of a specified character.
cmp() This function returns 1, if first list is “greater” than second list
max() return maximum element of given list
min() return minimum element of given list
all() Returns true if all element are true or if list is empty
any() return true if any element of the list is true. if list is empty, return false
len() Returns length of the list or size of the list
enumerate() Returns enumerate object of list
apply a particular function passed in its argument to all of the list elements returns a list containing
accumulate()
the intermediate results
filter() tests if each element of a list true or not
map() returns a list of the results after applying the given function to each item of a given iterable
This function can have any number of arguments but only one expression, which is evaluated and
lambda()
returned. By Ms. Preeti Kaushik
Example:
x=[34,56,783,2]
print("maximum number: ",max(x))
print("minimum number: ",min(x))
print("length of list: ",len(x))
print("sum of list elements: ",sum(x))

By Ms. Preeti Kaushik


Questions without using methods or built in function
1) Find sum, product and number of elements in the list
2) Search the element in the list and display whether it exist in the list or not.
Also print its position .
3) Find reverse of list
4) Find minimum number among list elements
5) Find maximum number among list element
6) Find number of even and odd number in the list. Also display their sum
7) Sort the elements of list
8) Replace all positive number by 1 , negative by -1 and no replacement for 0

By Ms. Preeti Kaushik


#Replace all positive number by 1 , negative by -1 and no replacement for 0

x=[23,-45,56,0]

for i in range(0,len(x)):
if x[i]>0:
x[i]=1
elif x[i]<0:
x[i]=-1
print(x)

Output: [1, -1, 1, 0]

By Ms. Preeti Kaushik


UNIT 2
Lists and Nested List: Introduction, Accessing list, Operations, Working
with lists, Library Functions and Methods with Lists.
Tuple: Introduction, Accessing tuples, Operations, Working, Library
Functions and Methods with Tuples.
Dictionaries :Introduction, Accessing values in dictionaries, Working
with dictionaries, Library Functions

By Ms. Preeti Kaushik


Tuple: Introduction
• A tuple is a collection which is ordered and unchangeable.
• A tuple is created by placing all the items (elements) inside parentheses (),
separated by commas. The parentheses are optional, however, it is a good
practice to use them.

• A tuple can have any number of items and they may be of different types
(integer, float, list, string, etc.).

By Ms. Preeti Kaushik


my_tuple = () # Empty tuple
print(my_tuple) # Output: ()

my_tuple = (1, 2, 3) # Tuple having integers


print(my_tuple) # Output: (1, 2, 3)

my_tuple = (1, "Hello", 3.4) # tuple with mixed datatypes


print(my_tuple) # Output: (1, "Hello", 3.4)

my_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) # nested tuple


print(my_tuple) # Output: ("mouse", [8, 4, 6], (1, 2, 3))

output
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))

By Ms. Preeti Kaushik


Tuple packing/unpacking
• A tuple can also be created without using parentheses. This is known as tuple packing.

Example:
my_tuple = 3, 4.6, "dog” #tuple packing
print(my_tuple) # Output: 3, 4.6, "dog"
a, b, c = my_tuple # tuple unpacking is also possible

print(a) #3
print(b) # 4.6
print(c) # dog

output
(3, 4.6, 'dog')
3
4.6
dog
By Ms. Preeti Kaushik
• Creating a tuple with one element is a bit tricky.

• Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is, in
fact, a tuple.
Example:
my_tuple = ("hello")
print(type(my_tuple)) # <class 'str'>

my_tuple = ("hello",) # Creating a tuple having one element


print(type(my_tuple)) # <class 'tuple'>

my_tuple = "hello", # Parentheses is optional


print(type(my_tuple)) # <class 'tuple’>

output
<class 'str'>
<class 'tuple'>
<class 'tuple'>
By Ms. Preeti Kaushik
How to access tuple element?
• tuple elements can be accessed by
a) Index
b) Negative indexing
c) Using slice operator

By Ms. Preeti Kaushik


a) indexing
• We can use the index operator [] to access an item in a tuple where the
index starts from 0.
• So, a tuple having 6 elements will have indices from 0 to 5. Trying to
access an element outside of tuple (for example, 6, 7,...) will raise an
IndexError.
• The index must be an integer; so we cannot use float or other types. This
will result in TypeError.
• nested tuples are accessed using nested indexing,

By Ms. Preeti Kaushik


Example:
my_tuple = ('p','e','r','m','i','t')

print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'

n_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) # nested tuple


# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) #4

output
p
t
s
4

By Ms. Preeti Kaushik


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

Example:
my_tuple = ('p','e','r','m','i','t')

print(my_tuple[-1]) # Output: 't'


print(my_tuple[-6]) # Output: 'p'

output
t
p

By Ms. Preeti Kaushik


c) slicing
• We can access a range of items in a tuple by using the slicing operator - colon “[m:n]".
Example:
my_tuple = ('p','r','o','g','r','a','m','i','z')

# elements 2nd to 4th


print(my_tuple[1:4])
output
('r', 'o', 'g')
# elements beginning to 2nd ('p', 'r')
print(my_tuple[:-7]) ('i', 'z')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
# elements 8th to end
print(my_tuple[7:])

# elements beginning to end


print(my_tuple[:])

By Ms. Preeti Kaushik


Changing a tuple
• tuples are immutable.
• This means that elements of a tuple cannot be changed once it has been
assigned. But, if the element is itself a mutable datatype like list, its nested
items can be changed.
• We can also assign a tuple to different values (reassignment).

Example:
my_tuple = (4, 2, 3, [6, 5])
my_tuple[1] = 9
Output: TypeError: 'tuple' object does not support item assignment

By Ms. Preeti Kaushik


Example 2:
my_tuple = (4, 2, 3, [6, 5])

# However, item of mutable element can be changed


my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])
print(my_tuple)

# Tuples can be reassigned output


my_tuple = ('p','r','o','g','r','a','m','i','z') (4, 2, 3, [9, 5])
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)

By Ms. Preeti Kaushik


+,*
• We can use + operator to combine two tuples. This is also called concatenation.

• We can also repeat the elements in a tuple for a given number of times using the * operator.

• Both + and * operations result in a new tuple.

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

By Ms. Preeti Kaushik


Deleting a tuple
• we cannot change the elements in a tuple. That also means we cannot
delete or remove items from a tuple.
• But deleting a tuple entirely is possible using the keyword del.

Example:
my_tuple = ('p','r','o','g','r','a','m','i','z')
#can't delete items
# TypeError: 'tuple' object doesn't support item deletion
del my_tuple[3]

Output:
TypeError: 'tuple' object doesn't support item deletion
By Ms. Preeti Kaushik
Example 2:
my_tuple = ('p','r','o','g','r','a','m','i','z')

# Can delete an entire tuple


Output:
del my_tuple
NameError: name 'my_tuple' is not defined

# NameError: name 'my_tuple' is not defined


print(my_tuple)

By Ms. Preeti Kaushik


Tuple methods
• Methods that add items or remove items are not available with tuple. Only the following two methods are
available.
Python Tuple Method
Method Description
count(x) Returns the number of items x
index(x) Returns the index of the first item that is equal to x

Example:
my_tuple = ('a','p','p','l','e',)

print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3

output
2
3
By Ms. Preeti Kaushik
Loop through tuple
• You can loop through the tuple items by using a for loop.

Example:
thistuple = ("apple", "banana", "cherry") Output:
apple
for x in thistuple:
banana
print(x) cherry

By Ms. Preeti Kaushik


Membership test
• To determine if a specified item is present in a tuple use the in keyword:

Example:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

Output:
Yes, 'apple' is in the fruits tuple

By Ms. Preeti Kaushik


Find ouput?

1)
my_tuple = ('a','p','p','l','e',)
print('a' in my_tuple)
print('b' in my_tuple)
print('g' not in my_tuple)

By Ms. Preeti Kaushik


• Len()
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))

Output: 3

By Ms. Preeti Kaushik


UNIT 2
Lists and Nested List: Introduction, Accessing list, Operations, Working
with lists, Library Functions and Methods with Lists.
Tuple: Introduction, Accessing tuples, Operations, Working, Library
Functions and Methods with Tuples.
Dictionaries :Introduction, Accessing values in dictionaries, Working
with dictionaries, Library Functions

By Ms. Preeti Kaushik


Introduction
• A dictionary maps a set of objects (keys) to another set of objects (values).
• A dictionary is a collection which is unordered, changeable and indexed.
• In Python dictionaries are written with curly brackets, and they have keys and values.
• Dictionaries are optimized to retrieve values when the key is known.
• Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated
distinctly.

example 1:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

output
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
By Ms. Preeti Kaushik
Dictionary creation
• Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
• An item has a key and the corresponding value expressed as a pair, key: value.
• While values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.

Example:
my_dict = {} # empty dictionary

my_dict = {1: 'apple', 2: 'ball’} # dictionary with integer keys

my_dict = {'name': 'John', 1: [2, 4, 3]} # dictionary with mixed keys

my_dict = dict({1:'apple', 2:'ball’}) # using dict()

my_dict = dict([(1,'apple'), (2,'ball’)]) # from sequence having each item as a pair


By Ms. Preeti Kaushik
Nested dictionaries
A dictionary can also contain many dictionaries, this is called nested
dictionaries.
Example:
# Creating a Nested Dictionary
# as shown in the below image
Dict = {1: 'Geeks', 2: 'For',
3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'Geeks'}}
print(Dict)

output
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}

By Ms. Preeti Kaushik


A dictionary can also contain many Create three dictionaries, than create
dictionaries, this is called nested dictionaries. one dictionary that will contain the other
three dictionaries:
Example:
myfamily = { child1 = {
"child1" : { "name" : "Emil",
"name" : "Emil", "year" : 2004
"year" : 2004 }
}, child2 = {
"name" : "Tobias",
"year" : 2007
"child2" : { }
"name" : "Tobias", child3 = {
"year" : 2007 "name" : "Linus",
}, "year" : 2011
}
"child3" : { myfamily = {
"name" : "Linus", "child1" : child1,
"year" : 2011 "child2" : child2,
} "child3" : child3
} }
By Ms. Preeti Kaushik
Accessing elements from dictionary
• While indexing is used with other container types to access values, dictionary uses
keys. Key can be used either inside square brackets or with the get() method.

Example 1:
my_dict = {'name':'Jack','age': 26}
print(my_dict['name']) # Output: Jack
print(my_dict.get('age')) # Output: 26

Output:
Jack
26
By Ms. Preeti Kaushik
The difference while using get() is that it returns None instead of KeyError, if the key is not found.

Example 2:
my_dict = {'name':'Jack', 'age': 26}
print(my_dict.get('address’))

Output:
None

Example 3:
my_dict = {'name':'Jack', 'age': 26}
# Trying to access keys which doesn't exist throws error
print(my_dict['address’])

Output:
KeyError: 'address'

By Ms. Preeti Kaushik


Change or add elements
• Dictionary are mutable. We can add new items or change the value of existing items using = operator.
• If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.

Example 1:
my_dict = {'name':'Jack', 'age': 26} output
{'name': 'Jack', 'age': 27}
my_dict['age'] = 27 # update value {'name': 'Jack', 'age': 27, 'address': 'Downtown'}

print(my_dict) #Output: {'age': 27, 'name': 'Jack'}

my_dict['address'] = 'Downtown’ # add item

print(my_dict) # Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}

By Ms. Preeti Kaushik


Remove or delete element
a) pop() : We can remove a particular item in a dictionary by using the method
pop(). This method removes as item with the provided key and returns the
value.

b) Popitem(): used to remove and return an arbitrary item (key, value) from
the dictionary.
The popitem() method removes the last inserted item (in versions before 3.7, a
random item is removed instead):

a) Clear(): ll the items can be removed at once using the clear().

b) Del keyword: keyword to remove individual items or the entire dictionary


itself.

By Ms. Preeti Kaushik


Example:
squares = {1:1, 2:4, 3:9, 4:16, 5:25} # create a dictionary

# remove a particular item


print(squares.pop(4)) # Output: 16

print(squares) # Output: {1: 1, 2: 4, 3: 9, 5: 25}

# remove an arbitrary item


print(squares.popitem()) # Output: (1, 1)

print(squares) # Output: {2: 4, 3: 9, 5: 25}

Output:
16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9} By Ms. Preeti Kaushik
Example 2:
squares = {1:1, 2:4, 3:9, 4:16, 5:25}

del squares[5] # delete a particular item


output
print(squares) {1: 1, 2: 4, 3: 9, 4: 16}
{}
squares.clear() # remove all items

print(squares) # Output: {}

Example 3:
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
del squares # delete the dictionary itself Output
NameError: name 'squares' is not defined
# Throws Error
print(squares)
By Ms. Preeti Kaushik
Copy a dictionary
• You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1
will automatically also be made in dict2.

Method 1: using copy()


Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Method 2: using dict()


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)

By Ms. Preeti Kaushik


Dictionary membership test
• We can test if a key is in a dictionary or not using the keyword in. Notice
that membership test is for keys only, not for values.

Example :
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(1 in squares)
print(2 not in squares) Output:
True
# membership tests for key only not value True
False
print(49 in squares) # Output: False

By Ms. Preeti Kaushik


Iterating /looping through a Dictionary
• Using a for loop we can iterate though each key in a dictionary
• When looping through a dictionary, the return value are the keys of the dictionary, but there are
methods to return the values as well.

Example 1: printing values


squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])

Output:
1
9
25
49
81

By Ms. Preeti Kaushik


Example 1: printing keys Example 3: printing values
thisdict = { "brand": "Ford", "model": thisdict = { "brand": "Ford“, "model": "Mustang", "year":
"Mustang","year": 1964 1964}
} for x in thisdict:
for x in thisdict: print(thisdict[x])
print(x) Output:
Ford
Output: Mustang
brand 1964
model
year
Example 4:printing values
thisdict = {"brand": "Ford","model": "Mustang","year":
Example 2: printing keys
1964 }
thisdict = { "brand": "Ford","model":
"Mustang","year": 1964 for x in thisdict.values():
} print(x)
Output:
print(thisdict.keys()) Ford
Mustang
Output: 1964
dict_keys(['brand', 'model', 'year']) By Ms. Preeti Kaushik
Loop through both keys and values, by using the items() function:

Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x, y in thisdict.items():
print(x, y)

Output:
brand Ford
model Mustang
year 1964

By Ms. Preeti Kaushik


Example:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict.keys())
print(thisdict.values())
print(thisdict.items())

Output:
dict_keys(['brand', 'model', 'year'])
dict_values(['Ford', 'Mustang', 1964])
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])

By Ms. Preeti Kaushik


Property of dictionary keys
1) More than one entry per key not allowed. Which means no duplicate key is allowed.
When duplicate keys encountered during assignment, the last assignment wins.
For example −
dict ={'Name':'Zara','Age':7,'Name':'Manni'}
print("dict['Name']:",dict['Name’])
Output:
dict['Name']: Manni

2) Keys must be immutable. Which means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed.
For example:
dict = {['Name']:'Zara','Age': 7}
print("dict['Name']: ", dict['Name’])
Output:
TypeError: unhashable type: 'list'
By Ms. Preeti Kaushik
cmp() function
• cmp() is an in-built function in Python, it is used to compare two objects and
returns value according to the given values. it returns negative, zero or
positive value based on the given input.
Syntax: cmp(obj1, obj2)
• Here, cmp() will return negative(1) if obj1<obj2, zero(0) if obj1=obj2,
positive (1) if obj1>obj2.

By Ms. Preeti Kaushik


Python Dictionary Methods
Method Description
clear() Remove all items form the dictionary.
copy() Return a shallow copy of the dictionary.

fromkeys(seq[, v]) Return a new dictionary with keys from seq and value equal to v (defaults to None).

get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to None).

items() Return a new view of the dictionary's items (key, value).

keys() Return a new view of the dictionary's keys.

Remove the item with key and return its value or d if key is not found. If d is not provided and key is not found,
pop(key[,d])
raises KeyError.

popitem() Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is empty.

setdefault(key[,d]) If key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None).

update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys.

values() Return a new view of the dictionary's values


By Ms. Preeti Kaushik
Dictionary comprehension
• A dictionary comprehension takes the form
{key: value for (key, value) in iterable}

Example 1: list for squares of number


myDict={x: x**2 for x in [1,2,3,4,5]} or myDict={x: x**2 for x in range(1,6)}
print(myDict)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

By Ms. Preeti Kaushik

You might also like