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

Session-8 Dictionary in Python

There are four main data types in Python: lists, tuples, sets, and dictionaries. Lists are ordered and changeable collections that allow duplicate elements. Tuples are ordered and unchangeable collections that allow duplicates. Sets are unordered and unindexed collections that do not allow duplicate elements. Dictionaries are unordered, changeable collections of key-value pairs that do not allow duplicate keys. Dictionaries are mutable, which means their contents can be changed after creation by adding, modifying, or removing key-value pairs. Common dictionary operations include accessing values by key, checking membership using "in" and "not in", and traversing the dictionary using a for loop.

Uploaded by

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

Session-8 Dictionary in Python

There are four main data types in Python: lists, tuples, sets, and dictionaries. Lists are ordered and changeable collections that allow duplicate elements. Tuples are ordered and unchangeable collections that allow duplicates. Sets are unordered and unindexed collections that do not allow duplicate elements. Dictionaries are unordered, changeable collections of key-value pairs that do not allow duplicate keys. Dictionaries are mutable, which means their contents can be changed after creation by adding, modifying, or removing key-value pairs. Common dictionary operations include accessing values by key, checking membership using "in" and "not in", and traversing the dictionary using a for loop.

Uploaded by

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

By – Amresh Tiwari (SGEI)

Data type identifies the type of data


values a variable can hold and the
operations that can be performed on
that data.
Variables can hold values of different
data types.

Python Data
Python is a dynamically typed language
Types hence we need not define the type of
the variable while declaring it.

The interpreter implicitly binds the value


with its type.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
In the Python programming language, there are
four collection data types :

List is a collection which is ordered and


changeable. Allows duplicate members.

Python Collections Tuple is a collection which is ordered and


unchangeable. Allows duplicate members.
(Arrays) Set is a collection which is unordered and
unindexed. No duplicate members.

Dictionary is a collection which is unordered,


changeable and indexed. No duplicate members.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


The data type dictionary fall under
mapping. It is a mapping between a set of
keys and a set of values.

The key-value pair is called an item. A key is


Python separated from its value by a colon(:) and
consecutive items are separated by
Dictionary commas.

Items in dictionaries are unordered, so we


may not get back the data in the same order
in which we had entered the data initially in
the dictionary.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Mutable and Immutable Data Types
• Variables whose values can be changed after they are created
and assigned are called mutable.
• Variables whose values cannot be changed after they are
created and assigned are called immutable.
• When an attempt is made to update the value of an immutable
variable, the old variable is destroyed and a new variable is
created by the same name in memory.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Mutable and Immutable Data Types

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Creating a dictionary
• To create a dictionary, the items entered are separated by
commas and enclosed in curly braces.
• Each item is a key value pair, separated through colon (:).
• The keys in the dictionary must be unique and should be of any
immutable data type, i.e., number, string or tuple. The values
can be repeated and can be of any data type.

Note: Dictionary is also known as associative array or mapping


or hashes.
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
Creating a dictionary…
• To create a dictionary, it is needed to collect pairs of key:value in “, -”.
• <dictionary-name>={ <key1>:<value1>,<key2>:<value2>,<key3>:<value3>. . . }
• #dict1 is an empty Dictionary created #curly braces are used for dictionary
>>> dict1 = {}
>>> dict1
{}
• #dict2 is an empty dictionary created using built-in function
>>> dict2 = dict()
>>> dict2
{}
• #dict3 is the dictionary that maps names of the students to respective marks in percentage
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92, ‘Punit':85}
>>> dict3
{'Amit': 95, ‘Sumit': 89, ‘Rumit': 92, ‘Punit': 85}

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Creating a dictionary…
• dict( ) constructor is used to create dictionary with the pairs of key and value. There
are various methods for this-
• #By passing Key:value pair as an argument:
>>> dict1 = dict(Amit=95,Sumit=89,Rumit=92,Punit=85)
>>> dict1
,'Amit': 95, ‘Sumit': 89, ‘Rumit': 92, ‘Punit': 85}
• Note:- No inverted commas were placed in argument but they came automatically in
dictionary.
• #By specifying Comma-separated key:value pair-
>>> dict2 = dict(,‘Amit':95,‘Sumit':89,‘Rumit':92, ‘Punit':85} )
>>> dict2
{'Amit': 95, ‘Sumit': 89, ‘Rumit': 92, ‘Punit': 85}

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Creating a dictionary…
• By giving Key:value pair in the form of separate sequence (By passing list):
>>> dict1 = dict(**‘Amit’,95+,*‘Sumit’,’89’+,*‘Rumit’,’92’+,*‘Punit’,’85’++)
>>> dict1
,'Amit': 95, ‘Sumit': 89, ‘Rumit': 92, ‘Punit': 85}
• By giving Key:value pair in the form of separate sequence (By passing tuple of list):
>>> dict1 = dict((*‘Amit’,95+,*‘Sumit’,’89’+,*‘Rumit’,’92’+,*‘Punit’,’85’+))
>>> dict1
,'Amit': 95, ‘Sumit': 89, ‘Rumit': 92, ‘Punit': 85}

• By giving Key:value pair in the form of separate sequence (By passing tuple of tuple):
>>> dict1 = dict(((‘Amit’,95),(‘Sumit’,’89’),(‘Rumit’,’92’),(‘Punit’,’85’)))
>>> dict1
,'Amit': 95, ‘Sumit': 89, ‘Rumit': 92, ‘Punit': 85}
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
The printing of the dictionary is
same as of the printing of
variables . the print() function is
used to print the dictionary.
Printing
dictionary
Syntax : print(dictionary_name)

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Accessing items in a dictionary
The items of a dictionary are accessed via the keys rather than via their relative positions or
indices. Each key serves as the index and maps to a value.

>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92, ‘Punit':85-

>>> dict3*‘Sumit']
89

# the key does not exist


>>> dict3['Shyam']
KeyError: 'Shyam'

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Dictionaries Are Mutable
Dictionaries are mutable which implies that the contents of the
dictionary can be changed after it has been created. i.e. we can-
• Add a new item
• Modify an Existing Item

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Add a new item in dictionary
Syntax:-
<dictionary>[<Key>]=<value>
Eg.-
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92,‘Punit':85}
>>> dict3*‘Navnit'] = 78
>>> dict3
,‘Amit':95,‘Sumit':89,‘Rumit':92,‘Punit':85,’Navnit’:78-

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Modify an Existing Item in dictionary
• The existing dictionary can be modified by just overwriting the key-
value pair.
• Syntax-
<dictionary>[<ExistingKey>]=<value>
Eg.-
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92,‘Punit':85}
#Marks of Rumit changed to 93.5
>>> dict3*‘Rumit'] = 93.5
>>> dict3
,‘Amit':95,‘Sumit':89,‘Rumit':93.5,‘Punit':85}
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
DICTIONARY Membership
OPERATIONS

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


• Python has two membership operators 'in' and
'not in'.
• The membership operator in checks if the key is
present in the dictionary and returns True, else it
returns False
• Syntax - <key> in <dictionary>
Membership Eg.-
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92,
‘Punit':85-
>>> ‘Sumit’ in dict3
True

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


• The not in operator returns True if the key is not
present in the dictionary, else it returns False.
• Syntax - <key> not in <dictionary>
Eg.-
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92,
‘Punit':85-
Membership… >>> ‘Sumit’ not in dict3
False

• Note:- in and not in does not apply on values,


they can only work with keys.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


TRAVERSING A DICTIONARY

We can access each item of the dictionary or traverse a


dictionary using for loop.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


TRAVERSING A DICTIONARY (Using for Loop)

• Method-1 :
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92, • Method 2
‘Punit':85- >>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92,
>>> for key in dict3: ‘Punit':85-
print(key,':',dict3[key]) >>> for key, value in dict3.items():
print(key,':',value)
Output:
Output:
Amit: 95
Amit: 95
Sumit: 89
Sumit: 89
Rumit: 92
Rumit: 92
Punit: 85
Punit: 85
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
TRAVERSING A DICTIONARY…

To access key and value we need to use keys() and values(). for
example-

• d.keys( ) function will display only key.


• d.values ( ) function will display value only.
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
What is Dictionary in Python? What are the features
of Python dictionary?
• The data type dictionary fall under mapping. It is a mapping between a set of keys and a set of
values.
• Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
Features of Python dictionary—
• Unordered set: dictionary is a unordered collection of key:value pairs.
• Not a sequence: like list, string and tuple , it is not a sequence because it is a collection of unordered
elements whereas a sequence is a collection of indexed numbers to keep them in order.
• Keys are used for its indexing because according to Python key can be of immutable type. String and
numbers are of immutable type and therefore can be used as a key.
• Keys should be unique : Because keys are used to identify values so they should be unique.
• Values of two unique keys can be same.
• Dictionary is mutable hence we can change value of a certain key.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


DICTIONARY METHODS AND BUILT-IN FUNCTIONS
• Python provides many functions to work on dictionaries.
• Some of them are –
len() dict() keys()
items() values() get()
update() del() clear()
fromkeys() copy() pop()
popitem() setdefault() copy()

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Finding the length of the dictionary
Returns the length or number of elements (key: value
pairs) in the dictionary passed as the argument
Syntax : len(<Dict_Name>)
For eg.-
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92, ‘Punit':85-
>>> len(dict3)
4

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


dict()
• Creates an empty dictionary • Creates a dictionary from a sequence of key-
if no argument is passed. value pairs
• Eg.- • Eg.-
pair1 = *(‘Amit',95),(‘Sumit',89), (‘Rumit',92),
>>> dict1 = dict() (‘Punit',85)]
>>> dict1 >>> pair1
*(‘Amit', 95), (‘Sumit', 89), (‘Rumit', 92), (‘Punit',
{} 85)]
>>> dict1 = dict(pair1)
>>> dict1
,‘Amit': 95, ‘Sumit': 89, ‘Rumit': 92, ‘Punit': 85}

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


keys()
• Returns a list of keys in the dictionary
• Eg.-
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92,
‘Punit':85-
>>> dict3.keys()
dict_keys([' Amit ', ' Sumit ', ' Rumit ', ' Punit '])

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


values()
• Returns a list of dictionary values
• Eg.-
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92,
‘Punit':85-
>>> dict3.values()
dict_values([95,89,92,85])

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


items()
• Returns all items of a dictionary in the form of tuple of
(key:value).
• Eg.-
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92, ‘Punit':85-
>>> dict3.items()
dict_items([(‘Amit‘,95),(‘Sumit‘,89),(‘Rumit‘,92),(‘Punit‘,85)])

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


get()
• Returns value of the given key, similar to
dictionary[key]. If not, then it will return None.
• Syntax : Dict_Name.get(key)
• Eg.-
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92, ‘Punit':85-
>>> dict3.get(‘Sumit’)
89

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


update()
• Updates the dictionary with the elements from
another dictionary.
• Syntax: dict.update([other])
• Eg.-
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92, ‘Punit':85-
>>> dict4 = ,‘Amit':100}
>>> dict3.update(dict4)
>>> dict3
,‘Amit':100,‘Sumit':89,‘Rumit':92, ‘Punit':85}
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
Deleting Elements from a Dictionary
• There are two methos for deleting elements
from a dictionary.
• Using del command
• Using pop() method

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


del command
• Delete a dictionary element.
• Syntax: del <dictionary_Name>[<key>]
• Eg.-
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92, ‘Punit':85-
>>> del dict3*‘Rumit’+
>>> dict3
,‘Amit':95,‘Sumit':89,‘Punit':85}

Note:- Python raises exception (KeyError) when try to delete a non-existent key.
Note:- del command removes the complete dictionary as an object.
Syntax: del <dictionary_Name>

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


pop() Method
• Delete a dictionary element.
• Syntax: <dictionary_Name>.pop(<key>)
• Eg.-
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92, ‘Punit':85-
>>> dict3.pop(‘Rumit’)
92
>>> dict3
,‘Amit':95,‘Sumit':89,‘Punit':85}

Note:- It also returns the corresponding value.


Note:- Python raises exception (KeyError) when try to delete a non-existent key.
Pop() method allows us to specify what to display when the given key does not
exist, rather than the default error message.
Syntax: <dictionary_Name>.pop(<key>, <Error-Message>)
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
popitem() Method
• Removes the last inserted key-value pair from the dictionary
and returns it as a tuple.
• Syntax: <dictionary_Name>.popitem()
• Eg.-
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92, ‘Punit':85-
>>> dict3.popitem()
(‘Punit‘, 85 )
>>> dict3
,‘Amit':95,‘Sumit':89,‘Rumit':92}

Note:- popitem() method return keyError if dictionary is empty.


By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
clear()
• Removes all items from the dictionary and the
dictionary becomes empty dictionary.
• Syntax: <dictionary>.clear()
• Eg.-
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92, ‘Punit':85-
>>> dict3.clear()
>>> dict3
{}
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
copy()
• Returns a shallow copy of the dictionary.
• Syntax: new_dict = original_dict.copy()
• Eg.-
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92, ‘Punit':85-
>>> dict4=dict3.copy()
>>> dict4
,‘Amit':95,‘Sumit':89,‘Rumit':92, ‘Punit':85}
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
fromkeys()
• Returns the dictionary with key mapped and
specific value. It creates a new dictionary from the
given sequence with the specific value.
• Syntax: dict_Name = fromkeys(seq, val)
• Eg.-
>>> s = ,‘Amit',‘Sumit‘,‘Rumit', ‘Punit'}
>>> dict3.fromkeys(s,10)
>>> dict3
,‘Amit':10,‘Sumit':10,‘Rumit':10, ‘Punit':10}
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
setdefault()
• Returns the value of a key (if the key is in dictionary). Else, it inserts a key
with the default value to the dictionary.
• Syntax: dict_Name.setdefault(key, default_value)
• Eg.-
>>> s = ,‘Amit':95,‘Sumit':89,‘Rumit':92, ‘Punit':85-
# when key already existing in dictionary
>>> dict3.setdefault(‘Sumit’,100)
>>> dict3
,‘Amit':95,‘Sumit':89,‘Rumit':92, ‘Punit':85-
# when key not existing in dictionary
>>> dict3.setdefault(‘Sandeep’,100)
>>> dict3
,‘Amit':95,‘Sumit':89,‘Rumit':92, ‘Punit':85, ‘Sandeep’:100-

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Assignment…
• “Lists and dictionary are mutable”. Explain.
• What advantages do dictionary have over lists?
• What is membership operator? Explain its use
with the help an example.
• How is del D and del D[<key>] different from
one another if D is a dictionary?
• How is clear() function different from del
<dict_name> statement?
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
PROGRAMMING PROBLEMS EXAMPLES
Write a program to enter names of employees and their salaries as input and store them in a
dictionary.
num = int(input("Enter the number of employees whose data to be stored: "))
count = 1 Output:
employee = dict() #create an empty dictionary Enter the number of employees to be stored: 5
Enter the name of the Employee: 'Tarun'
while count <= num: Enter the salary: 12000
name = input("Enter the name of the Employee: ") Enter the name of the Employee: 'Amina'
salary = int(input("Enter the salary: ")) Enter the salary: 34000
Enter the name of the Employee: 'Joseph'
employee[name] = salary Enter the salary: 24000
count += 1 Enter the name of the Employee: 'Rahul'
Enter the salary: 30000
print("\n\nEMPLOYEE_NAME\tSALARY") Enter the name of the Employee: 'Zoya'
for k in employee: Enter the salary: 25000
EMPLOYEE_NAME SALARY
print(k,'\t\t',employee[k])
'Tarun' 12000
Amina' 34000
'Joseph' 24000
Rahul' 30000
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel) 'Zoya' 25000
PROGRAMMING PROBLEMS EXAMPLES
Write a program to count the number of times a character appears in a given string.
st = input("Enter a string: ")
dic = {} #creates an empty dictionary
for ch in st:
Output:
if ch in dic: #if next character is already in the dictionary
dic[ch] += 1 Enter a string: HelloWorld
else: H:1
dic[ch] = 1 #if ch appears for the first time
for key in dic: e:1
print(key,':',dic[key]) l:3
o:2
W:1
r:1
d:1
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
PROGRAMMING PROBLEMS EXAMPLES
Write a function to convert a number entered by the user into its corresponding number in words. For
example, if the input is 876 then the output should be ‘Eight Seven Six’.

num = input("Enter any number: ") #number is stored as string


print("The number is:",num)
numberNames = {0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',5:'Five',6:'Six',7:'Seven', 8:'Eight',9:'Nine'}
result = ''
for ch in num:
key = int(ch) #converts character to integer Output:
value = numberNames[key]
Enter any number: 6512
result = result + ' ' + value
print("The numberName is:",result) The number is: 6512
The numberName is: Six Five One Two

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


PROGRAMMING PROBLEMS
Write a program to input your friends’ names and
their Phone Numbers and store them in the
dictionary as the key-value pair.
Perform the following operations on the dictionary:
a) Display the name and phone number of all your friends
b) Add a new key-value pair in this dictionary and display the
modified dictionary
c) Delete a particular friend from the dictionary
d) Modify the phone number of an existing friend
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
What will be the output of the following code segment:
Consider the following dictionary stateCapital:
stateCapital = {"AndhraPradesh":"Hyderabad", "Bihar":"Patna",
"Maharashtra":"Mumbai", "Rajasthan":"Jaipur"}
Find the output of the following statements:
I. print(stateCapital.get("Bihar"))
II. print(stateCapital.keys())
III. print(stateCapital.values())
IV. print(stateCapital.items())
V. print(len(stateCapital))
VI. print("Maharashtra" in stateCapital)
VII. print(stateCapital.get("Assam"))
VIII. del stateCapital["Rajasthan"]
print(stateCapital)

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)

You might also like