Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

SUBJECT:COMPUTER SCIENCE

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

Accessing keys or values simultaneously


dictionary.keys()-returns all keys defined in dictionary
dictionary.values()-returns all values defined in dictionary
example:
phonedict={"madhav":1234567,"steven":765890,"sampree":4673215,"rabiya":3223567}
print( phonedict.keys())
print(phonedict.values())
output:
dict_keys(['madhav', 'steven', 'sampree', 'rabiya'])
dict_values([1234567, 765890, 4673215, 3223567])
Convert dictionary to list
Example:
phonedict={"madhav":1234567,"steven":765890,"sampree":4673215,"rabiya":3223567}
L_keys=list(phonedict.keys())
L_values=list(phonedict.values())
print(L_keys)
print(L_values)
output:
['madhav', 'steven', 'sampree', 'rabiya']
[1234567, 765890, 4673215, 3223567]
Characteristics of dictionary
1.Unordered set:
it is an unordered set of key,value pair
2.Not a sequence:
as it in unordered,the sequence are not indexed.
3.Indexed by keys,not numbers:
dictionary are indexed by keys.strings or numbers or tuple can be used as a key as they
are mutable
4.Key must be unique:
each key must be unique.
however two unique keys can have same values

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

Checking for existence of a key


key> in<dictionary>
<key>not in<dictionary>
Example:
dict={"vowels1":"a","vowels":"e","vowels3":"i"}
print("vowels" in dict) # True
print("vowels4" in dict) #False
● Membership operators are applicable only for keys not for values.
Print("a" in dict1) #false
Print("a" in dict1.values()) #true

(1)Write the output for the following Python codes.


A={1:100,2:200,3:300,4:400,5:500}
print (A.items())
print (A.keys())
print (A.values())
answer:
dict_items([(1, 100), (2, 200), (3, 300), (4, 400), (5, 500)])
dict_keys([1, 2, 3, 4, 5])
dict_values([100, 200, 300, 400, 500]
(2)Find the output for the following code:
adict={'bhavana':1,"richard":2,"firoza":10,"arshnoor":20}
temp=0
for value in adict.values():
Page 6 of 8
temp=temp+value
print(temp)
ans:
33
(3)Find the output for the following code:
adict={'bhavana':1,"richard":2,"firoza":10,"arshnoor":20}
temp=""
for key in adict:
if temp<key:
temp=key
print(temp)
ans:
Richard
(4)Find the output for the following:
myDict={ 'a':27, 'b':43,'c' :25,'d':30}
valA=''
for i in myDict:
if i > valA:
valA=i
valB= myDict[i]
print (valA) #Line1
print (valB) #Line2
print (30 in myDict) #Line3
#Write the output of the Line 1,2 ,3
Ans:
d
30
False
(5)Write a python program that takes a value and checks whether the given value is a part of
dictionary.if not print error message
Ans:
dict1={0:"zero",1:"one",2:"two",3:"three"}
n=input("enter a value:")
for key in dict1:
if dict1[key]==n:
print ("the value is present at",key)
break;
else:
print("value not found")
(6)write a program to create a dictionary containing names of competition winner as
keys,number of wins as their 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

You might also like