Professional Documents
Culture Documents
DICTIONARIES
DICTIONARIES
CHAPTER:DICTIONARIES
GRADE XI
What is a 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.
� Internally dictionaries are arranged on the basis of the keys
Creating an empty Dictionary
1.Empty curly braces
� Dict = {}
� print("Empty Dictionary: ")
� print(Dict)
2.Using dictionary constructor
employee=dict()
print(employee)
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(:).
Example:
� dict={‘Subject':‘InformaticPractices','Class':‘11’}
�
Key=‘subject’,’class’
Value=‘informaticPractices’,’11’
# Creating a Dictionary with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
# Creating a Dictionary with dict() method
Specifying comma separated key value pair
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
Specifiying key value pair in form of sequence
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Page 1 of 8
Dict = dict([[1, 'Geeks'], [2, 'For']])
Arguments to dict contains key value pair as tuple or list separated by commas
# Creating a Nested Dictionary
Dict = {1: 'Geeks', 2: 'For', 3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'Geeks'}}
print(Dict)
Adding elements to dictionary
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements one at a time
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[2] = 'Welcome'
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}}
Accessing elements from a Dictionary
● in order to access the items of a dictionary refer to its key name.
● Key can be used inside square brackets.
● There is also a method called get() that will also help in acessing the element from a
dictionary.
● in dictionary,the elements are unordered.one cannot access the elements as per specific
order
example:
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# accessing a element using key
print(Dict['name’]) #For
# accessing a element using key
print(Dict[1]) #Geeks
# accessing a element using get()
print(Dict.get(3)) #Geeks
#attemptimg to acces a key that doesnot exist cause error
Print(Dict[5])) >>keyerror
Traversing a dictionary
For loop to access and process the elements in dictionary
for <item> in dictionary:
process each item
Page 2 of 8
Loop variable item will be assigned the keys of dictionary one by one
Example:
d1={5:"number","a":"string",(1,2):"tuple"}
for key in d1:
print(key,":",d1[key])
answer:
5 : number #order of assignment of keys differs from
a : string #what we store as dictionary is unordered
(1, 2) : tuple
Page 3 of 8
example:
dict={"finch":10,"myna":13,"peacock":10,"myna":20}
>>> dict
{'finch': 10, 'myna': 20, 'peacock': 10}
5.Mutable:
can change the value of certain key
<dictionary>[<key>]=<values>
Example:
dict={'finch': 10, 'myna': 20, 'peacock': 10}
>>> dict["myna"]=30
>>> dict
{'finch': 10, 'myna': 30, 'peacock': 10}
Example:
Can even add new key:value pair .key should be unique .if key already exist it updates the
corresponding value
dict["parrot"]=30
>>> dict
{'finch': 10, 'myna': 30, 'peacock': 10, 'parrot': 30}
6.Internally stored as mapping:
Key:value pair are associated with one another with internal function hashing.this way of
linking is called mapping
Deleting elements from dictionary
1.To delete a dictionary element(key-value pair)
del<dictionary>[key]
example:
dict={"vowels1":"a","vowels":"e","vowels3":"i"}
del dict["vowels1"]
print(dict)
output:
{'vowels': 'e', 'vowels3': 'i’}
When try to delete a key that doesnot exist it generates keyerror
2.To delete a dictionary element(key-value pair) using pop() .Also returns the corresponding
value
<dictionary>.pop(key)
Example:
dict={"vowels1":"a","vowels":"e","vowels3":"i"}
dict.pop("vowels1“)
a
{'vowels': 'e', 'vowels3': 'i’}
<dictionary>.pop(key,’in-case of error show me’)
Example:
Page 4 of 8
dict.pop(“vowels”,”not found”)
>>>not found
<dictionary>.clear() Method
Remove all elements
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()
print(car)
output:
{}
<Dictionary>.get(key,[default]) Method
Get the value of the key,if no key found displays error.user can give error message as a second
argument.
Example:
� car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.get("model")
print(x) #Mustang
Car.get(“carno”,”no key found”);
<Dictionary>.items() Method
Returns a list containing a tuple for each key value pair
Example:
dict1={"vowels1":"a","vowels":"e","vowels3":"i"}
mylist=dict1.items()
for x in mylist:
print(x)
answer:
('vowels1', 'a')
('vowels', 'e')
('vowels3', 'i')
<Dictionary>.items() Method
as items() returns two values ,write a loop with two variables to access key value pairs
Example:
dict1={"vowels1":"a","vowels":"e","vowels3":"i"}
Page 5 of 8
mylist=dict1.items()
for key,val in mylist:
print(key,val)
answer:
vowels1 a
vowels e
vowels3 i
<dictionary>.update(<other-directory>)
Updates the dictionary with the specified key-value pairs
� car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"color": "White"})
If same key then it will override the values
Page 7 of 8
Ans:
n=int(input("enter the number of students:"))
compwinners={}
for i in range(n):
key=input("enter winner name")
value=int(input("enter number of prices:"))
compwinners[key]=value
print(compwinners)
(7)What type of objects can be used as keys in dictionaries? Also explain why?
(8)What is a dictionary in Python? How can we access data from a dictionary? What is the main
use of a dictionary?
(9)Write a Python command to delete an item “Address” from the given dictionary ‘student’ ? 1
>>>student = {“Name”:”Surbhi”, “Roll No”:”11”, “Address”: “Sec-7 New Delhi”}
Page 8 of 8