Class 11 - CS - Dictionary
Class 11 - CS - Dictionary
Example:
Example:
>>> D1={[2,3]:"hello"}
TypeError: unhashable type: 'list'
Characteristics of a Dictionary
1. Unordered Set
A dictionary is an unordered set of key:value pairs .Its values can contain references to any type of
object
2. Not a Sequence
Unlike a string, list, tuple a dictionary is not a sequence because it is unordered set of
elements.The sequences are indexed by a range of ordinal numbers.
3. Indexed by keys , Not Numbers
4. Keys must be unique
5. Mutable:
Like lists, dictionaries are also mutable.We can change the value of a certain key “in place” using
the assignment statement
<dict>[<key>]=<value>
You can even add a new key:value pair to a dictionary using a simple assignment statement. But the
key being added should be unique. If the key already exists, then value is simply changed. 6. Internally
stored as Mappings
Internally, the key:value pairs of a dictionary are associated with one another with some
internal function(called hash-function).This way of linking is called mapping.
Creating a dictionary using dict( ) Constructor:
A. use the dict( ) constructor with single parentheses:
>>> marks=dict(Physics=75,Chemistry=78,Maths=81,CS=78)
>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
B. dict ( ) constructor using parentheses and curly braces: >>>
marks=dict({"Physics":75,"Chemistry":78,"Maths":81, "CS":78})
>>> marks
{
'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
Syntax:
dictionary-name[key]
Example:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81,
"CS":78 } >>> marks["Maths"]
81
>>> marks["English"] #Access a key that doesn’t exist causes an
error KeyError: 'English'
Lookup : A dictionary operation that takes a key and finds the corresponding value, is
called lookup.
Example to convert the sequence returned by keys() and values()
functions by using list()
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
>>> list(marks.keys())
['physics', 'Chemistry', 'Maths', 'CS’]
>>> list(marks.values())
[75, 78, 81, 78]
TRAVERSING A DICTIONARY: Syntax:
Syntax:
del dictionary-name[key]
Example:
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
>>> del marks['English']
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
II. Using pop( ) method:
It deletes the key-value pair and returns the value of deleted element.
Syntax:
dictionary-name.pop( )
Example: >>> marks
To check the existence of a key in dictionary, two operators are used: (i) in : it
returns True if the given key is present in the dictionary, otherwise False. (ii) not
in : it returns True if the given key is not present in the dictionary, otherwise
False.
Example:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> 'Chemistry' in marks
True
>>> 'CS' not in marks
False
>>> 78 in marks # in and not in only checks the existence of keys not values False
However, if you need to search for a value in dictionary, then you can use
in operator with the following syntax:
Syntax:
value in dictionary-name. values( )
Example:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> 78 in marks.values( )
True
Nested Dictionary
In Python, a nested dictionary is a dictionary inside a dictionary. It's a
collection of dictionaries into one single dictionary.
output:
{1: {'name': 'John', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Marie', 'age': '22', '
'sex': 'Female}}
Access the elements using the [ ]
Output
John
27
Male
PRETTY PRINTING A DICTIONARY:
dumps( ) function prints key:value pair in separate lines with the number of
spaces which is the value of indent argument.
import json
d1={"roll":2,"Name":"Riya","English":45,"Csc":49,'phy':34,'che':55,'bio':66
} print(json.dumps(d1,indent=2))
print(d1)
DICTIONARY FUNCTIONS:
Consider a dictionary marks as follows:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
• fromkeys()
• The fromkeys() method creates a new dictionary from the given sequence of elements with a
value provided by the user.
dictionary.fromkeys(sequence[, value])
fromkeys() Parameters
value (Optional) - value which is set to each each element of the dictionary
fromkeys() method returns a new dictionary with the given sequence of elements as the keys of the
dictionary.
# vowels keys vowels = dict.fromkeys(keys)
keys = {'a', 'e', 'i', 'o', 'u' } print(vowels)
OUTPUT vowels = dict.fromkeys(keys, value)
{'a': None, 'u': None, 'o': None, 'e': print(vowels)
None, 'i': None}
# vowels keys OUTPUT
keys = {'a', 'e', 'i', 'o', 'u' }
value = 'vowel' {'a': 'vowel', 'u': 'vowel', 'o': 'vowel', 'e':
'vowel', 'i': 'vowel'}
#Example1
d1=dict.fromkeys([2,4,6,8],100)
print(d1)
d2=dict.fromkeys([12,14,16,18])
print(d2)
Your school has decided to deposit scholarship amount of 2500 to some selected students.
Write a program to input the selected student's roll num
and create a dictionary for the same.'''
'''l1=[]
n=int(input("How many students:")) #2
for a in range(n): #2,a=0,a=1
r=int(input("Enter Rollno:"))#12 20
l1.append(r) #[12,20]
s=dict.fromkeys(l1,2500)
print("Created dictionary")
print(s)
Making a shallow copy using copy() method
• Creating copy using assignment operator
Creating copy using copy()
copy() method returns a shallow copy of the dictionary. It doesn't modify the original
dictionary.
pop()
The pop() method removes the specified item from the
dictionary. • Syntax
dictionary.pop(keyname, defaultvalue)
popitem()
The popitem() method removes the item that was last inserted into the dictionary. In
versions before 3.7, the popitem() method removes a random item. The removed
item is the return value of the popitem() method, as a tuple
#deleting elements-
clear(),del,pop(),popitems()
stu={1:'Neha',2:'Sona',3:'Sohan',4:'Preeti'}
stu.pop(2)
stu.pop(6)
print(stu)
stu.popitem() #delete last entered item.LIFO
order stu.clear()
print(stu)
Sorted() – return the sorted list of dictionary keys
s={'roll':3,'name':"riya",'Csc':60,'English':58
} d=sorted(s)
d1=sorted(s,reverse=True)
d2=sorted(s.keys())
d3=sorted(s.values())
print(d)
print(d1)
print(d2)
print(d3)
d4=sorted(s.items())
print(d4)
max(),min(),sum()
s={2:32,4:45,5:60,6:58}
print(min(s))
mi=min(s.values())
print(mi)
print("\nmaximum")
print(max(s))
ma=max(s.values())
print(ma)
print("\nsum")
print(sum(s))
su=sum(s.values())
print(su)
THANK YOU