0% found this document useful (0 votes)
58 views7 pages

Dictionaries

Uploaded by

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

Dictionaries

Uploaded by

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

Dictionaries

A dictionary is an unordered sequence of key-value pairs.


 Key and value in a key-value pair in a dictionary are separated by a colon. Further, the key : value pairs
in a dictionary are separated by commas and are enclosed between curly parentheses.
 The keys of the dictionaries are immutable types such as Integers or Strings etc.
 Indices in a dictionary can be of any immutable type and are called keys.
 Dictionaries are mutable.

Creating Dictionaries
A Dictionary can be created in three different ways:
Empty Dictionary
>>>D = { } # Empty Dictionary
Dictionary using literal notation
>>>D = {“Name” : “Mohan”, “Class” : “XI”, “City” : “Gurdaspur”}
>>>print(D)
{“Name” : “Mohan”, “Class” : “XI”, “City” : “Gurdaspur”}
>>>print(D[“City”])
“Gurdaspur”
Dictionary using dict() function
Dict() function is used to create a new dictionary with no items. For example,
>>> Months = dict() # Creates an empty dictionary
>>>print(Month) # Prints an empty dictionary
We can use Square Brackets( [ ] with keys for accessing and initializing dictionary values. For Example:
>>> Months[0] = ‘January’
>>> Months[1] = ‘February’
>>>Months[2] = ‘March’
>>> print(Months)
{0 : ’January’, 1: ’February’ , 2 : ’March’}

>>> Months = dict(Jan = 31, Feb = 28, March = 31) # Creating dictionary by giving values in dict()
function
>>> print(Months)
{‘Jan’ : 31, ‘Feb’ : 28, ‘March’ : 31}

Accessing Elements of a Dictionary


Elements of Dictionary may be accessed by writing the Dictionary name and key within square brackets
([ ] ) as given below:
>>> D = {0 : “Sunday”, 1 : “Monday”, 2: “Tuesday”}
>>> print(D[1])
Monday

Attempting to access a key that does not exist, causes an error. Consider the following statement that
is trying to access a non – existent key (7) from dictionary D. it raises KeyError.
>>> D[7]
KeyError : 7

Traversing a Dictionary
Dictionary items can be accessed using a for loop.
for x in D:
print(D [x])

Output
Sunday
Monday
Tuesday

Mutability of Dictionary
Dictionary like lists are mutable, it means dictionary can be changed, new items can be added and
existing items can be updated.

Adding an Element in Dictionary


We can add new element (key : value pair) to a dictionary using assignment, but the key being added
must not exist in dictionary and must be unique.
>>> D[4] = “Wednesday” # if a new key is given, new item is added
>>> print(D)
{0 : “Sunday”, 1 : “Monday”, 2: “Tuesday”, 3: “Wednesday”}

Updating / Modifying an element in Dictionary


We can change the individual element of dictionary as given below:
>>> D[1] = “Mon” # Value of Key (1) is changed
>>> print(D)
{0 : “Sunday”, 1 : “Mon”, 2: “Tuesday”, 3: “Wednesday”}

Dictionary Functions and Methods


Built –in functions and methods are provided by Python to manipulate Python dictionaries.

len() function:
It is used to find the length of the dictionary, i.e., the count of the key : value pair.
Exp.
D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
length = len(D)
print("Length of Dictionary : ", length)

Output
Length of Dictionary : 4

dict() function:
The dict() function creates a dictionary.
Exp.
By giving Key:value pair in the form of separate sequence:

Accessing Items, Keys and Values – get(), items(), keys(), values () methods
get( ) Method : it returns value of the given key
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> value = D.get('Rama', 'Key not Found')
>>> print("Age of Rama is : ", value)

>>> value = D.get('Mohit', 'Key not Found') # if key is not in the dictionary, it shows key not found
>>> print("Age of Mohit is : ", value)

Output
Age of Rama is : 22
Age of Mohit is : Key not Found

items( ) Method :
It returns all items of a dictionary in the form of list of tuple of (key:value)
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> print(D.items())

Output
dict_items([('Ram', 20), ('Mohan', 30), ('Rama', 22), ('Rashi', 32)])

keys( ) Method :
It returns list of all the keys of the dictionary.
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> print(D.keys())

Output
dict_keys(['Ram', 'Mohan', 'Rama', 'Rashi'])

values( ) Method :
It returns list of all the values of the dictionary.
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> print(D.values())

Output
dict_values([20, 30, 22, 32])

update( ) Method :
This function merges key : value pairs from the new dictionary into the original dictionary, adding or replacing
as needed. The items in the new dictionary are added to the old one and override any items already there with
the same keys.
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> D2 = {'A' : 20, 'Mohan' : 60, 'Rama' : 62, 'B' : 32}
>>> D.update(D2)
>>> print("D => ",D)
>>> print("D2 => ", D2)

Output
D => {'Ram': 20, 'Mohan': 60, 'Rama': 62, 'Rashi': 32, 'A': 20, 'B': 32}
D2 => {'A': 20, 'Mohan': 60, 'Rama': 62, 'B': 32}

Deleting elements from dictionary:


del statement
del statement is used to delete a dictionary element or dictionary entry, i.e., a key:value pair.
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> print(D)
>>> del D["Mohan"] # to delete a key from the dictionary i.e. “Mohan”
>>> print(D)
>>> del D # To delete the whole dictionary
Output

{'Ram': 20, 'Mohan': 30, 'Rama': 22, 'Rashi': 32} # Complete Dictionary
{'Ram': 20, 'Rama': 22, 'Rashi': 32} # After deleting “Mohan”

clear ( ) method
It empties the dictionary.
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> print(D)
>>> D.clear()
>>> print("Dictionary after Clear : ", D)

Output
{'Ram': 20, 'Mohan': 30, 'Rama': 22, 'Rashi': 32}
Dictionary after Clear : {}

pop ( ) method
It removes and returns the dictionary element associated to passed key.
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> print("Removed Item : ", D.pop("Rama"))

Output
Removed Item : 22

popitem ( ) method
It removes and returns the last dictionary element.
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> print("Removed Item : ", D.popitem())

Output
Removed Item : ('Rashi', 32)

sorted ( ) method
It returns a sorted list of the dictionary keys. It is used as below:
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> print(sorted(D)) # sort the keys in ascending order
>>> print(sorted(D), reverse = False) # sort the keys in ascending order
>>> print(sorted(D), reverse = True) # sort the keys in descending order

Output
['Mohan', 'Ram', 'Rama', 'Rashi']
['Mohan', 'Ram', 'Rama', 'Rashi']
['Rashi', 'Rama', 'Ram', 'Mohan']

max ( ) , min() and sum() Functions


These functions work with the keys of a dictionary. Dictionaries must be homogeneous to use the
functions.
 max() function gives the maximum value
 min() function gives the minimum value
 sum() function gives the sum of keys
>>> D = {1: "Monday", 2: "Tuesday", 3:"Wednesday"}
>>> print("Max = ",max(D))
>>> print("min = ",min(D))
>>> print("Sum = ", sum(D))
Output
Max = 3
min = 1
Sum = 6

fromkeys ( ) method
This method is used to create a new dictionary from a sequence containing all the keys and common
value, which will be assigned to all the keys. Keys argument must be an interable sequence (First argument).
When value not given, it will take None as the values for the keys (Second Argument)
Exp.
>>> D = dict.fromkeys([2,4,5,8],200) # When Value given
>>> print(D)
>>> D = dict.fromkeys([2,4,5,8]) # When value not given, it will take None as the values for the keys
print(D)

Output
{2: 200, 4: 200, 5: 200, 8: 200}
{2: None, 4: None, 5: None, 8: None}

setdefault ( ) method
This method inserts a new key: value pair only if the key does not exist. If the key already exists, it
returns the current value of the key.
Exp.
>>> D = {1: "Monday", 2: "Tuesday", 3:"Wednesday"}
>>> D.setdefault(2,"Tuesday") # Key already exists, it will not insert
>>> print(D)
>>> D.setdefault(4,"Thursday") # New Key, it will be inserted
>>> print(D)

Output
{1: 'Monday', 2: 'Tuesday', 3: 'Wednesday'}
{1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday'}

Q) Write a program to count number of words in a string?


str = "This is a book , book is very good"
D = {}
w = str.split()
for x in w:
key = x
if key not in D:
count = w.count(key)
D[key] = count
print("Count Frequencies...")
print(D)
Output:
Count Frequencies...
{'This': 1, 'is': 2, 'a': 1, 'book': 2, ',': 1, 'very': 1, 'good': 1}

Q) Write a program to count number of characters in a string?


str = "This is a book , book is very good"
D = {}
for x in str:
if x not in D:
count = str.count(x)
D[x] = count
print("Count Frequencies...")
print(D)
Output:
Count Frequencies...
{'T': 1, 'h': 1, 'i': 3, 's': 3, ' ': 8, 'a': 1, 'b': 2, 'o': 6, 'k': 2, ',': 1, 'v': 1, 'e': 1, 'r': 1, 'y': 1, 'g': 1, 'd': 1}

MCQs
1 Dictionaries are ………………….. set of elements. C
(a) sorted (b) Ordered (c) unordered (d) random
2 Which of the following will create a dictionary with given keys and a common value? A
(a) fromkeys() (b) update () (c) setdefault() (d) all of the above
3 What will be printed by the following statements? B
D1 = {“cat”:12,”dog”:6,”elephant”:23,”bear”:20}
Print(25 in D1)
(a) True (b) False (c) Error (d) None
4 What would the following code print? B
D = {‘spring’ : ‘autumn’, ‘autumn’: ’fall’, ‘fall’ : ‘spring’}
Print(d[‘autumn’])
(a) autumn (b) fall (c) spring (d) Error
5 What will be the output of following Python code? C
d1 = {“a” : 10, “b” : 2, “c”:3}
str1 = “ ”
for i in d1:
str1 = str1 + str(d1[i]) + “ “
str2 = str1[:-1]
print(str2[::-1])
(a) 3, 2 (b) 3,2,10 (c) 3,2,01 (d) Error

Question – Answers
Q1) What is a dictionary?
Ans: A dictionary is an unordered sequence of key-value pairs.
 Key and value in a key-value pair in a dictionary are separated by a colon. Further, the key : value pairs
in a dictionary are separated by commas and are enclosed between curly parentheses.
 The keys of the dictionaries are immutable types such as Integers or Strings etc.
 Indices in a dictionary can be of any immutable type and are called keys.
 Dictionaries are mutable.

Q2) What is the use of fromkeys ( ) method?


Ans: This method is used to create a new dictionary from a sequence containing all the keys and common
value, which will be assigned to all the keys. Keys argument must be an interable sequence (First argument).
When value not given, it will take None as the values for the keys (Second Argument)

Q3) What do you understand by Mutability of Dictionary?


Ans: Dictionary is mutable, it means dictionary can be changed, new items can be added and existing items
can be updated.

Q4) Why a list cannot be used as keys of dictionaries?


Ans: Lists cannot be used as keys in a dictionary because they are mutable and a Python dictionary can have
only keys of immutable types.

Q5) If the addition of new key : value pair causes the size of the dictionary to grow beyond its original size,
an error occurs, True or False?
Ans: False, There cannot occur an error because dictionaries being the mutable types, they can grow or shrink
on and as needed basis.
Q6) Write the output of following code:
x = {1:10, 2:20, 3:30}
x[4] = 20
print(x)
Ans:
{1: 10, 2: 20, 3: 30, 4: 20}

Q7) Write the output of following code:


d = {'x': 1, 'y': 2, 'z': 3}
for k in d:
print (k, '=', d[k])
Ans:
x=1
y=2
z=3

Q8) Write the output of following code:


x = {1:10}
d = {2:20, 3:30, 4:40}
x.update(d)
print(x)
Ans:
{1: 10, 2: 20, 3: 30, 4: 40}

You might also like