0% found this document useful (0 votes)
26 views8 pages

Lab9 - Dictionaries Done

Uploaded by

emanshaikh999
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)
26 views8 pages

Lab9 - Dictionaries Done

Uploaded by

emanshaikh999
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
You are on page 1/ 8

Fall 2021, CS 112 Lab 09: Introduction to Dictionary

Programming Fundamentals

USMAN INSTITUTE OF TECHNOLOGY

Department of Computer Science and Software


Engineering
CS112 Programming Fundamentals

Lab# 09
Introduction to
Dictionary
Objective:
This lab provides the students the concept of dictionary and its operations.

Name of Student:

Roll No: Sec.

Date of Experiment:

Marks Obtained/Remarks:

Signature:

1
Fall 2021, CS 112 Lab 09: Introduction to Dictionary
Programming Fundamentals
Lab 09: Introduction to Dictionary

Introduction to Dictionary

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.
Following are some basic information about dictionary data structures.
i. A dictionary in Python is an unordered set of key: value pairs.
ii. Unlike lists, dictionaries are inherently order less. The key: value pairs appear to be
in a certain order but it is irrelevant.
iii. Each KEY must be unique, but the VALUES may be the same for two or more keys.
iv. If you assign a value to a key then later in the same dictionary have the same key
assigned to a new value, the previous value will be overwritten.
v. Instead of using a number to index the items (as you would in a list), you must use
the specific key, e.g., calling UITDict['Python'].

Dictionary Methods to Extract the Data

There are three dictionary methods for extracting certain data.


<dictionary>.keys( ) returns the keys in the dictionary as a list (sort of), and
<dictionary>.values( ) returns the dictionary values as a list (sort of).
Why "sort of"? Because the returned objects are not a list -- they are their own list-like
types, called dict_keys and dict_values.

Program 1: Write a Python program to store the information of a student in a dictionary data
structure.

Code:
dict = { 'Name': 'Jibran', 'Age': 13, 'Class':'Seventh',
'DOB':'16 April 2006'}
print("dict['Name']: ", dict['Name'])
print("dict['Age']: ", dict['Age'])
print("dict['DOB']: ", dict['DOB'])
print("dict['Class']:", dict['Class'])

Program 2: Using for loop to access the values stored inside the dictionary.

Code:
dict = { 'Name': 'Jibran', 'Age': 13, 'Class':'Seventh',
'DOB':'16 April 2006'}
for x in dict:
print(dict[x])

2
Fall 2021, CS 112 Lab 09: Introduction to Dictionary
Programming Fundamentals
Compare output of Program 1 and Program 2:

Program 3: Using for loop to access the values inside the dictionary by using values()
function.

Code:
dict = { 'Name': 'Jibran', 'Age': 13, 'Class':'Seventh',
'DOB':'16 April 2006'}
for x in dict.values():
print(x)

Program 4: Write a program which will extract both the keys and their corresponding
values by using item() from a given dictionary. Keep in mind this time you need two
variables to get the function return item() which is key : value.

Code:
dict = { 'Name': 'Jibran', 'Age': 13, 'Class':'Seventh',
'DOB':'16 April 2006'}
for x, y in dict.items(): #tuple unpacking
print(x, y)

Program 5: Write a program which will search the key from a dictionary and print a
message that it has found a key from the given dictionary. [HINT: Use if condition to find
the key from the dictionary.]

Code:
dict = { 'Name': 'Jibran', 'Age': 13, 'Class':'Seventh',
'DOB':'16 April 2006'}

if "DOB" in dict:
print("Yes, 'DOB' is one of the keys in the dict
dictionary")

3
Fall 2021, CS 112 Lab 09: Introduction to Dictionary
Programming Fundamentals
Adding New Items Inside Existing Dictionary:

Adding an item to the dictionary is done by using a new index key and assigning a value to
it. We can even change the value of exiting keys by reassign a new value.

Program 6: Write a program which will add some new information inside the exiting
dictionary. Use a concept to update the previous keys with their values and add new
information as well.

Code:
dict = { 'Name': 'Jibran', 'Age': 13, 'Class':'Seventh',
'DOB':'16 April 2006'}

dict['Age'] = 12.5
dict['School'] = 'The Seeds School'

print("dict['Age']: ", dict['Age'])


print("dict['School']: ",
dict['School']) dict['Friend1'] =
'Mohib' dict['Friend2'] = 'Akbar'
dict['Friend3'] = 'Jazil'

print("dict['Friend1']", dict['Friend1'])
print("dict['Friend2']", dict['Friend2'])
print("dict['Friend3']", dict['Friend3'])

Removing Items from the Dictionary


There are several methods to remove items from a dictionary, Such as pop(), del , etc.

Removing Items from the Dictionary using POP( )


The pop( ) method removes the item with the specified key name. Note: In versions before 3.7, a
random item is removed instead .

Program 7: Use pop( ) to remove the key and its item from the exiting dictionary.

Code:
dict = { 'Name': 'Jibran', 'Age': 13, 'Class':'Seventh',
'DOB':'16 April 2006', 'School': 'The Seeds School',
'Friend1':'Mohib', 'Friend2':'Akbar', 'Friend3':'Jazil' }
for x, y in dict.items():
print(x, y)
dict.pop("Friend1")
print(dict)

4
Fall 2021, CS 112 Lab 09: Introduction to Dictionary
Programming Fundamentals

Removing Items from the Dictionary using DEL( )


The del keyword removes the item with the specified key name.

Program 8: Write a program which will add some new information inside the exiting
dictionary. Use a concept to update the previous keys with their values and add new
information as well.

Code:
dict = { 'Name': 'Jibran', 'Age': 13, 'Class':'Seventh',
'DOB':'16 April 2006'}

dict['Age'] = 12.5
dict['School'] = 'The Seeds School'
print("dict['Age']: ", dict['Age'])
print("dict['School']: ", dict['School'])
dict['Friend1'] = 'Mohib'
dict['Friend2'] =
'Akbar' dict['Friend3']
= 'Jazil'

print("dict['Friend1']" , dict['Friend1'])
print("dict['Friend2']" , dict['Friend2'])
print("dict['Friend3']" , dict['Friend3'])
del dict ['Friend1']

Removing Items from the Dictionary using popitem( )

The popitem( ) method removes the last inserted item (in versions before 3.7, a random
item is removed instead).

Program 9: Write a program which will delete the last key with value from the exiting
dictionary. Print the remaining dictionary. [Hint: Use pop( ) to delete from the last based
on FILO.]

dict = { 'Name': 'Jibran', 'Age': 13, 'Class':'Seventh',


'DOB':'16 April 2006', 'School': 'The Seeds School',
'Friend1':'Mohib', 'Friend2':'Akbar', 'Friend3':'Jazil' }

print(dict)
for x, y in dict.items():
print(x, y)
dict.popitem()
print("After poping from the dictionary the remaining
elements are: ",dict)

5
Fall 2021, CS 112 Lab 09: Introduction to Dictionary
Programming Fundamentals

Nested Dictionary

We can use a dictionary inside a dictionary. This can be helpful when creating telephone directories
or records etc.

Program 10: Write a record set for the faculty members of Computer Science Department. Using
the concept of nested dictionary or nested dictionary.

Code:
faculty = {1: {'name': 'Syed Faisal Ali', 'experience': '22',
'gender': 'Male'},
2: {'name': 'Dr. M Wasim', 'experience': '23',
'gender': 'Male'},
3: {'name': 'Dr. Lubaid', 'experience': '23',
'gender': 'Male'},
4: {'name': 'Noor ul Huda', 'experience': '3',
'gender': 'Female'},
5: {'name': 'Parkash Lohana', 'experience': '19',
'gender': 'Male'},
6: {'name': 'Fauzan Saeed', 'experience': '15',
'gender': 'Male'}}

print(faculty)

6
Fall 2021, CS 112 Lab 09: Introduction to Dictionary
Programming Fundamentals

Programming Exercise

1. Design a dictionary of your family. Once you get the printout update family dictionary
with your grandparents (maternal and paternal) including uncles and aunts (maternal and
paternal).

2. Write a function to design a personal phone directory of your parents and


friends. You must add 12 members. Then make a function to delete a member
from a telephone directory. Print total number of members in your personal
phone directory.
3. Write a function reverse() that takes as input a phone book, that is, a dictionary
mapping names (the keys) to phone numbers (the values). The function should
return another dictionary representing the reverse phone book mapping phone
numbers (the keys) to the names (the values)

4. Write a function hexASCII( ) that prints the correspondence between the


lowercase characters in the alphabet and the hexadecimal representation of their
ASCII code. Note: [A format string and the format string method can be used to
represent a number value in hex notation.]

You might also like