Computer Science
Class XI( As per CBSE Board)
Chapter 14
Dictionary
New
syllabus
2023-24
Visit : python.mykvs.in for regular updates
2.
Dictionary
It is anunordered collection of items where each
item consist of a key and a value.
It is mutable (can modify its contents ) but Key must
be unique and immutable.
Visit : python.mykvs.in for regular updates
3.
Creating A Dictionary
Itis enclosed in curly braces {} and each item is separated from other item by a
comma(,). Within each item, key and value are separated by a colon (:).Passing
value in dictionary at declaration is dictionary initialization.get() method is used to
access value of a key
e.g.
dict = {‘Subject': ‘Informatic Practices', 'Class': ‘11'}
Accessing List Item
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print(dict)
print ("Subject : ", dict['Subject'])
print ("Class : ", dict.get('Class'))
OUTPUT
{'Class': '11', 'Subject': 'Informatics Practices'}
('Subject : ', 'Informatics Practices')
('Class : ', 11)
Visit : python.mykvs.in for regular updates
Dictionary
4.
Iterating / Traversingthrough A Dictionary
Following example will show how dictionary items can be accessed through loop.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
for i in dict:
print(dict[i])
OUTPUT
11
Informatics Practices
Updating/Manipulating Dictionary Elements
We can change the individual element of dictionary.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
dict['Subject']='computer science'
print(dict)
OUTPUT
{'Class': 11, 'Subject': 'computer science'}
Visit : python.mykvs.in for regular updates
Dictionary
5.
Deleting Dictionary Elements
del,pop() and clear() statement are used to remove
elements from the dictionary.
del e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print('before del', dict)
del dict['Class'] # delete single element
print('after item delete', dict)
del dict #delete whole dictionary
print('after dictionary delete', dict)
Output
('before del', {'Class': 11, 'Subject': 'Informatics Practices'})
('after item delete', {'Subject': 'Informatics Practices'})
('after dictionary delete', <type 'dict'>)
Visit : python.mykvs.in for regular updates
Dictionary
6.
pop() method isused to remove a particular item in a
dictionary. clear() method is used to remove all
elements from the dictionary.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print('before del', dict)
dict.pop('Class')
print('after item delete', dict)
dict.clear()
print('after clear', dict)
Output
('before del', {'Class': 11, 'Subject': 'Informatics Practices'})
('after item delete', {'Subject': 'Informatics Practices'})
('after clear', {})
Visit : python.mykvs.in for regular updates
Dictionary
7.
Built-in Dictionary Functions
S.No.Function & Description
1
len(dict)Gives the total length of the dictionary. It is equal to
the number of items in the dictionary.
dict = {'Name': 'Aman', 'Age': 37};
print ("Length : %d" % len (dict))
OUTPUT ->2
2
str(dict)Return a printable string representation of a
dictionary
3
type(variable)If variable is dictionary, then it would return a
dictionary type.
Visit : python.mykvs.in for regular updates
Dictionary
8.
Built-in Dictionary Methods
S.No.Method & Description
1
dict() - creates dictionary
x = dict(name = “Aman", age = 37, country = “India")
Here x is created as dictionary
2
keys() - returns all the available keys
x = dict(name = “Aman", age = 37, country = “India")
print(x.keys())
OUTPUT->dict_keys(['country', 'age', 'name'])
3
values() - returns all the available values
x = dict(name = “Aman", age = 37, country = “India")
print(x.values())
OUTPUT->dict_values(['India', 37, 'Aman'])
Visit : python.mykvs.in for regular updates
Dictionary
9.
Built-in Dictionary Methods
S.No.Method & Description
4
items() - return the list with all dictionary keys with values.
x = dict(name = "Aman", age = 37, country = "India")
print(x.items())
OUTPUT->dict_items([('country', 'India'), ('age', 37), ('name', 'Aman')])
5
update()-used to change the values of a key and add new keys
x = dict(name = "Aman", age = 37, country = "India")
d1 = dict(age= 39)
x.update(d1,state="Rajasthan")
print(x)
OUTPUT-{'country': 'India', 'age': 39,'name':'Aman','state': 'Rajasthan'}
Visit : python.mykvs.in for regular updates
Dictionary
10.
Built-in Dictionary Methods
S.No.Method & Description
6
del -used to remove key
x = dict(name = "Aman", age = 37, country = "India")
del x['age']
print(x)
OUTPUT->{'country': 'India', 'name': 'Aman'}
del x -> will remove complete dictionary
7
fromkeys() – is used to create dictionary from keys
keys = {'a', 'e', 'i', 'o', 'u' }
value ="Vowel"
vowels = dict.fromkeys(keys, value)
print(vowels)
OUTPUT-> {'i': 'Vowel', 'u': 'Vowel', 'e': 'Vowel', 'a': 'Vowel', 'o': 'Vowel'}
Visit : python.mykvs.in for regular updates
Dictionary
11.
Built-in Dictionary Methods
S.No.Method & Description
8
copy() - returns a shallow copy of the dictionary.
x = dict(name = "Aman", age = 37, country = "India")
y=x.copy()
print(y)
print(id(x))
print(id(y))
OUTPUT - >{'country': 'India', 'age': 37, 'name': 'Aman'}
33047872
33047440
9
popitem() – removes last item from dictionary
x = dict(name = "Aman", age = 37, country = "India")
x.popitem()
print(x)
OUTPUT-> {'age': 37, 'name': 'Aman'}
Visit : python.mykvs.in for regular updates
Dictionary
12.
Built-in Dictionary Methods
S.No.Method & Description
10
setdefault() method returns the value of the item with the specified key.
If the key does not exist, insert the key, with the specified value.
x = dict(name = "Aman", country = "India")
y=x.setdefault('age',39)
print(y)
OUTPUT-> 39
11
max() – returns key having maximum value
Tv = {'a':100, 'b':1292, 'c' : 88}
Keymax = max(Tv, key=Tv.get)
print(Keymax)
OUTPUT-> b
12 min()- returns key having minimum value
Visit : python.mykvs.in for regular updates
Dictionary
13.
Built-in Dictionary Methods
S.No.Method & Description
13
sorted- sort by key or value
dict1 = {'b':100, 'a':12, 'c' : 88}
y = sorted(dict1.items(),key=lambda x: x[1],reverse=True)
print(y)
OUTPUT-> [('b', 100), ('c', 88), ('a', 12)]
Visit : python.mykvs.in for regular updates
Dictionary
14.
count the numberof times a character appears in agiven
string using a dictionary
input_string = "python.mykvs.in"
frequencies = {}
for char in input_string:
if char in frequencies:
frequencies[char] += 1
else:
frequencies[char] = 1
print ("Per char frequency in '{}' is :n {}".format(input_string,
str(frequencies)))
OUTPUT
Per char frequency in 'python.mykvs.in' is :
{'i': 1, 'h': 1, 'k': 1, 'm': 1, 'o': 1, 'n': 2, 'p': 1, 's': 1, 't': 1, 'v': 1, 'y': 2, '.': 2}
Visit : python.mykvs.in for regular updates
Dictionary
15.
create a dictionarywith names of employees, their
salary and access them
employees =
{'Aman':{'salary':'10000'},'Mayur':{'salary':'51000'}}
employee1 = employees['Aman']
print(employee1)
OUTPUT
{'salary': '10000'}
Visit : python.mykvs.in for regular updates
Dictionary
16.
Questions.
1. Create dictionaryto store 4 student details with
rollno,name,age field.Search student in list.
2. Create dictionary for month and noofdays for a
year. User is asked to enter month name and
system will show no of days of that month.
Visit : python.mykvs.in for regular updates
Dictionary