0% found this document useful (0 votes)
60 views16 pages

Dictionary 14

The document discusses dictionaries in Python. It explains that a dictionary is a mutable collection of key-value pairs where keys must be unique and immutable. It provides examples of creating, accessing, iterating through, updating, deleting from dictionaries and built-in dictionary functions and methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views16 pages

Dictionary 14

The document discusses dictionaries in Python. It explains that a dictionary is a mutable collection of key-value pairs where keys must be unique and immutable. It provides examples of creating, accessing, iterating through, updating, deleting from dictionaries and built-in dictionary functions and methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

New

syllabus
Chapter 14 2023-24
Dictionary

Computer Science
Class XI ( As per CBSE Board)

Visit : python.mykvs.in for regular updates


Dictionary

It is an unordered 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


Dictionary
Creating A Dictionary
It is 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
Iterating / Traversing through 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

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

pop() method is used 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

Built-in Dictionary Functions


S.No. Function & Description
len(dict)Gives the total length of the dictionary. It is equal to
the number of items in the dictionary.
1 dict = {'Name': 'Aman', 'Age': 37};
print ("Length : %d" % len (dict))
OUTPUT ->2
str(dict)Return a printable string representation of a
2 dictionary

type(variable)If variable is dictionary, then it would return a


dictionary type.
3

Visit : python.mykvs.in for regular updates


Dictionary

Built-in Dictionary Methods


S.No. Method & Description
dict() - creates dictionary
1 x = dict(name = “Aman", age = 37, country = “India")
Here x is created as dictionary
keys() - returns all the available keys
x = dict(name = “Aman", age = 37, country = “India")
2
print(x.keys())
OUTPUT->dict_keys(['country', 'age', 'name'])
values() - returns all the available values
x = dict(name = “Aman", age = 37, country = “India")
3
print(x.values())
OUTPUT->dict_values(['India', 37, 'Aman'])

Visit : python.mykvs.in for regular updates


Dictionary
Built-in Dictionary Methods
S.No. Method & Description
items() - return the list with all dictionary keys with values.
x = dict(name = "Aman", age = 37, country = "India")
4
print(x.items())
OUTPUT->dict_items([('country', 'India'), ('age', 37), ('name', 'Aman')])
update()-used to change the values of a key and add new keys
x = dict(name = "Aman", age = 37, country = "India")
5 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
Built-in Dictionary Methods
S.No. Method & Description
del -used to remove key
x = dict(name = "Aman", age = 37, country = "India")
del x['age']
6
print(x)
OUTPUT->{'country': 'India', 'name': 'Aman'}
del x -> will remove complete dictionary
fromkeys() – is used to create dictionary from keys
keys = {'a', 'e', 'i', 'o', 'u' }
value ="Vowel"
7
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
Built-in Dictionary Methods
S.No. Method & Description
copy() - returns a shallow copy of the dictionary.
x = dict(name = "Aman", age = 37, country = "India")
y=x.copy()
print(y)
8 print(id(x))
print(id(y))
OUTPUT - >{'country': 'India', 'age': 37, 'name': 'Aman'}
33047872
33047440
popitem() – removes last item from dictionary
x = dict(name = "Aman", age = 37, country = "India")
9 x.popitem()
print(x)
OUTPUT-> {'age': 37, 'name': 'Aman'}

Visit : python.mykvs.in for regular updates


Dictionary
Built-in Dictionary Methods
S.No. Method & Description
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")
10
y=x.setdefault('age',39)
print(y)
OUTPUT-> 39
max() – returns key having maximum value
Tv = {'a':100, 'b':1292, 'c' : 88}
11 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

Built-in Dictionary Methods


S.No. Method & Description
sorted- sort by key or value
dict1 = {'b':100, 'a':12, 'c' : 88}
13 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

count the number of 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

create a dictionary with 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

Questions.
1. Create dictionary to 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

You might also like