Xia2 CH12 Lect1
Xia2 CH12 Lect1
Lecture: 1
DICTIONARY – KEY: VALUE PAIRS:
Dictionaries are mutable, unordered collections with elements in the form or a key: value
pairs that associate keys to values.
Creating a Dictionary:
To create a dictionary, we include the key : value pairs in curly braces as per following
syntax:
<dictionary – name> = { <key>:<value>, <key>: <value> …..}
Example:
Note 1:
Internally, dictionaries are indexed (i.e., arranged) on the basis of keys.
Note 2:
Dictionaries are also called associated arrays or mappings or hashes.
PRG 1:
Write a program to read roll numbers and marks of four students and create a directory
from it having roll numbers as keys.
print('='*52)
rno = []
mks = []
for a in range(4):
r, m =eval(input('Enter roll no and marks respectively :'))
rno.append(r)
mks.append(m)
D ={rno[0]: mks[0], rno[1] : mks[1], rno[2]: mks[2], rno[3]: mks[3]}
print('-'*52)
print('Dictionary Created....')
print(D)
print('='*52))
OR
1
print('='*52)
D={}
for a in range(4):
r, m =eval(input('Enter roll no and marks respectively :'))
D[r]=m
print('-'*52)
print('Dictionary Created....')
print(D)
print('='*52)
Output:
====================================================
Enter roll no and marks respectively :10, 90
Enter roll no and marks respectively :12, 80
Enter roll no and marks respectively :13, 79
Enter roll no and marks respectively :18, 82
----------------------------------------------------
Dictionary Created....
{10: 90, 12: 80, 13: 79, 18: 82}
====================================================
Example:
teachers = {'Simple': 'Computer Science', 'Madhu' : 'Sociology',
'Harpreet': 'Science', 'Raman' :'Mathematics'}
2
PRG 2:
Write a program to create a dictionary namely Numerals from following two lists.
Keys = [‘One’, ‘Two’ , ’Three’]
Values= [1, 2, 3]
====================================================
Given two lists are ['One', 'Two', 'Three'] [1, 2, 3]
Dictionary created with these lists is
{'One': 1, 'Two': 2, 'Three': 3}
====================================================
PRG 3:
Write a program to create a dictionary containing names of competition
winner students as keys and number of their wins as values.
print('='*52)
N = int(input("How many students?"))
CW = {}
for i in range(N):
KEY =input('Name of the student :')
VALUE = int( input('Number of competitions won :'))
CW[KEY]=VALUE
print('The dictionary now is:')
print('-'*52)
print(CW)
print('='*52)
Output:
====================================================
How many students?3
Name of the student :AMAN
Number of competitions won :5
Name of the student :AMIR
Number of competitions won :3
Name of the student :ALAM
Number of competitions won :7
The dictionary now is:
----------------------------------------------------
{'AMAN': 5, 'AMIR': 3, 'ALAM': 7}
====================================================
3