NAVODAYA VIDYALAYA SAMITI� HYDERABAD REGION
E-CONTENT
COMPUTER SCIENCE CLASS XI
COMPUTATIONAL THINKING AND PROGRAMMING-1
DICTIONARY IN PYTHON
SHIFA JAMES
PGT CS , JNV KADAPA
CONTENTS
Learning Objectives
After completing this lesson, the students should be able to:
INTRODUCTION
Dictionary - Definition
A Dictionary is an unordered collection of items where each item is a key-value pair.
It is a mapping between a set of keys and a set of values. The key-value pair is called an item.
Elements of a Dictionary are enclosed in curly brackets { } and are separated by commas.
Dictionaries are mutable data types in the form of key:value , where key is used to access the corresponding Value .
Keys are unique within a dictionary and are of immutable data types whereas Values are of mutable types
Internally stored as Mappings
Internally, the key:value pair are associated with one another with some internal function(called hash function). This way of linking is called as mapping
Creating a Dictionary
Teachers = {“Rajeev”:”Math”, “Amal”:”Physics”, ”Arun”:”Chemistry“ , “ SJ”:”CS” }
In above given example :
Key-value pair | Key | Value |
“Rajeev”:”Math” | “Rajeev” | “Math” |
“Amal”:”Physics” | “Amal” | “Physics” |
“Arun”:”Chemistry” | “Arun” | “Chemistry” |
“SJ”:”CS” | “SJ” | “CS” |
Different methods of creating a Dictionary
1) dict1 is an empty Dictionary created . Curly braces are used for empty dictionary
Example :
>>> dict1 = {}
>>> dict1
{}
>>> dict2 = dict()
>>> dict2
{}
Different methods of creating a Dictionary
3) dict3 is the dictionary that maps names of the students to respective marks in percentage
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict3
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
Accessing keys and values simultaneously
Characteristics of a Dictionary
Characteristics of a Dictionary
For example
Data = {1:100, 2:200,3:300,4:200}
So, to change value of dictionary the format is :
DictionaryName[“key” / key ]=new_value
You can even add new key:value pair using the same format:
DictionaryName[“key” / key ]=new_value
Accessing Elements in a Dictionary
For example :
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict3['Ram']
89
>>> dict3['Sangeeta']
85
>>> dict3['Shyam'] #the key does not exist
KeyError: 'Shyam'
DICTIONARIES ARE MUTABLE
Add new item, Update an item , Delete an item
Adding elements to Dictionary
We can add a new item to the dictionary as shown in the following example:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict1['Meena'] = 78
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85, 'Meena': 78}
Note : The new item added will be at the end of the dictionary
Updating elements in Dictionary
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
#Marks of Suhel changed to 93.5
>>> dict1['Suhel'] = 93.5
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5, 'Sangeeta': 85}
Deleting elements from Dictionary
Method 1 - Using del command
del dictionaryName[“Key”]
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> del dict1[‘Ram’]
>>> dict1
{'Mohan':95, 'Suhel':92, 'Sangeeta':85}
Note :
If you try to remove the item whose key does not exists, the python runtime error occurs.
Deleting elements from Dictionary
Method 2 - Using pop() function
Syntax :
dictionaryName.pop([“Key”])
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict1.pop(‘Suhel’)
>>>dict1
{'Mohan':95,'Ram':89, 'Sangeeta':85}
Note:
if key passed to pop() doesn’t exists then python will raise an exception.
Traversing a Dictionary
We can access each item of the dictionary or traverse a dictionary using for loop.
Method 1
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
for key in dict1:
print(key , ':‘ , dict1[key])
Output
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Traversing a Dictionary
for key,value in dict1.items():
print(key,':',value)
Output
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Dictionary Operations – �Membership operator – in
The membership operator in checks if the key is present in the dictionary and returns True, else it returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> 'Suhel' in dict1
True
Dictionary Operations – �Membership operator – not in
The not in operator returns True if the key is not present in the dictionary, else it returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> 'Suhel' not in dict1
False
Dictionary Methods and Built-in Functions
Method | Description | Example |
len() | Returns the length or number of key: value pairs of the dictionary passed as the argument | >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> len(dict1) 4 |
dict() | Creates a dictionary from a sequence of key-value pairs | pair1 = [('Mohan',95),('Ram',89), ('Suhel',92),('Sangeeta',85)] >>> pair1 [('Mohan', 95), ('Ram', 89), ('Suhel', 92), ('Sangeeta', 85)] >>> dict1 = dict(pair1) >>> dict1 {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85} |
get() | Returns the value corresponding to the key passed as the argument If the key is not present in the dictionary it will return None | >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict1.get('Sangeeta') 85 >>> dict1.get('Sohan') >>> |
Dictionary Methods and Built-in Functions
Method | Description | Example |
keys() | Returns a list of keys in the dictionary | >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict1.keys() dict_keys(['Mohan', 'Ram', 'Suhel', 'Sangeeta']) |
values() | Returns a list of values in the dictionary | >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict1.values() dict_values([95, 89, 92, 85]) |
items() | Returns a list of tuples(key – value) pair | >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict1.items() dict_items([( 'Mohan', 95), ('Ram', 89), ('Suhel', 92), ('Sangeeta', 85)]) |
clear() | Deletes or clear all the items of the dictionary | >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict1.clear() >>> dict1 { } |
Dictionary Methods and Built-in Functions
Method | Description | Example |
update() | appends the key-value pair of the dictionary passed as the argument to the key-value pair of the given dictionary | >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict2 = {'Sohan':79,'Geeta':89} >>> dict1.update(dict2) >>> dict1 {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85, 'Sohan': 79, 'Geeta': 89} >>> dict2 {'Sohan': 79, 'Geeta': 89} |
popitem() | It will remove the last dictionary item and return key,value. of the removed item | >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> k,v = dict1.popitem() >>> print(k,”: “ v) Sangeeta :85 |
copy() | it will create a copy of dictionary. | >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dic2 = dict1.copy() |
Dictionary Methods and Built-in Functions
Method | Description | Example |
fromkeys() | return new dictionary with the given set of elements as the keys of the dictionary. Note: Set of elements should be immutable type | >>>seq = ('name', 'age', 'sex') >>>dict = dict.fromkeys(seq) >>>print ("New Dictionary : “ , str(dict) ) New Dictionary : {'age': None, 'name': None, 'sex': None} >>>dict = dict.fromkeys(seq, 10) >>>print ("New Dictionary : " , str(dict) ) New Dictionary : {'age': 10, 'name': 10, 'sex': 10} |
setdefault() | returns the value of the item with the specified key. If the key does not exist, insert the key, with the specified value, | >>>car = { "brand": "Ford", “model": "Mustang", "year": 1964 }�>>>x = car.setdefault("color", "white“)�>>>print(x) white |
Dictionary Methods and Built-in Functions
Method | Description | Example |
sorted() | this function is used to sort the key or value of dictionary in either ascending or descending order. By default it will sort the keys. To display in descending order | >>> Dict1 = {1: 111, 4: 444 , 3: 300, 5: 555 , 2: 222} >>> print(sorted(Dict1)) {1: 111, 2: 222, 3: 300, 4: 444, 5: 555} >>>print(sorted(Dict1, reverse = ‘True’)) {5:555,4:444, 3:333 , 2:222 , 1:111} |
min() | This function returns lowest value in dictionary, this will work only if all the values in dictionary is of numeric type | >>> Dict1 = {1: 111, 4: 444 , 3: 300, 5: 555 , 2: 222} >>>print(min(Dict1.values())) 111 |
max() | This function returns highest value in dictionary, this will work only if all the values in dictionary is of numeric type | >>> Dict1 = {1: 111, 4: 444 , 3: 300, 5: 555 , 2: 222} >>>print(max(Dict1.values())) 555 |
SUGGESTED PROGRAMS
Program 1
#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:
if ch in dic: #if next character is already in the dictionary
dic[ch] += 1
else:
dic[ch] = 1 #if ch appears for the first time
for key in dic:
print(key,':',dic[key])
Output:
Enter a string: HelloWorld
H : 1
e : 1
l : 3
o : 2
W : 1
r : 1
d : 1
Program 2
#Program to create a dictionary which stores names of the employee and their salary
num = int(input("Enter the number of employees whose data to be stored: "))
count = 1
employee = dict() #create an empty dictionary
while count <= num:
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
count += 1
print (‘\nDetails of Employees ‘)
print("\n\nEMPLOYEE_NAME\tSALARY\n~~~~~~~~~~~~~~~~~")
for k in employee:
print(k,'\t\t',employee[k])
Output
Enter the number of employees to be stored: 5
Enter the name of the Employee: 'Tarun'
Enter the salary: 12000
Enter the name of the Employee: 'Amina'
Enter the salary: 34000
Enter the name of the Employee: 'Joseph'
Enter the salary: 24000
Enter the name of the Employee: 'Rahul'
Enter the salary: 30000
Enter the name of the Employee: 'Zoya‘
Enter the salary: 25000
Details of Employees
EMPLOYEE_NAME SALARY
~~~~~~~~~~~~~~~~~~~~~~~~~~
'Tarun' 12000
'Amina' 34000
'Joseph' 24000
'Rahul' 30000
'Zoya' 25000
Summary
BIBLIOGRAPHY:
1. Computer Science Textbook for class XI
by NCERT
2. Computer Science with Python
by Sumita Arora
3. Computer Science with Python
by Preeti Arora