Matrix Computers (Page 1 of 5)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
Chapter 9 Dictionary
Dictionary is the unordered collection of key-value pairs where the value can be
any python object whereas the keys are the unique immutable objects, i.e., Numbers,
string or tuple but not list or set or dict. Dictionary can be created by using multiple key-
value pairs enclosed within the curly braces{} and separated by the colon (:).
d={1:"Aryan",2:"Janvi"} #Here 1 is key and "Aryan" is value
Empty dictionary:-
d={}
# or
d=dict()
type(d) <class dict>
No indexing:-
d={1:"Aryan",2:"Janvi"}
print(d[0]) #it will not work
No slicing:-
we can iterate on keys only:-
d={"name": "Ayush","age": 22}
for i in d:
print(i) #it will print keys only
for key in d:
print(key,d[key])
for key,value in d1: #error
print(key,value)
We can access dictionary elements through key not through index:-
d={"name":"Ayush","age":22}
print(d["name"]) #Ayush
print(d["age"]) #22
No ordering:-
{1:"Aryan",2:"Janvi"}=={2:"Janvi",1:"Aryan"} #True
Dictionary is mutable:-
d["age"]=25
We can add new key value pair:-
print(d["fees"]) #error
d["fees"]=10000 it will add a new key value pair
Matrix Computers (Page 2 of 5)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
Converting dictionary into list:-
l=list(d) #it will copy only keys
Keys are unique it will overlap value if duplicate key:-
d={1:"A",1:"B",1:"C"}
print(d[1]) #C
dictionary comprehension technique:-
d={i:i**3 for i in range(1,6)}
d={i:input(f"Enter number {i}") for i in range(1,3)}
dict():-
l=[1,2,3,4]
d=dict(l) #error because only keys
l=[(1,"A"),(2,"B"),(3,"C")]
d=dict(l) #allowed
Matrix Computers (Page 3 of 5)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
Built-in functions:-
SN Function Description
1 len(dict) It is used to calculate the length of the dictionary.
2. max(dict)
3. min(dict)
4. sum(dict)
5 str(dict) It converts the dictionary into the printable string
representation.
6 type(variable) It is used to print the type of the passed variable.
7 zip()
Examples:-
print(len(d))
print(str(d))
print(type(d))
zip()
key=[1,2,3]
values=["A","B","C"]
d=dict(zip(key,values))
List as a value:-
marks={101:[70,80,90],102:[70,80,90]}
or
n=int(input("Enter how many students:"))
d={}
for i in range(1,n+1):
roll,*marks=input("Enter roll and marks of 3 subjects").split()
roll=int(roll)
marks=list(map(int,marks))
d[roll]=marks
print(d)
Built-in Dictionary methods (members of dict class)
SN Method Description
1 dic.clear() It is used to delete all the items of the dictionary but not the
dictionary itself.
2 dict.copy() It returns a shallow copy of the dictionary.
d1={1:[1,2,3]}
d2=d1.copy()
d2[1][0]=10 #This will also change d1
import copy
d3=copy.deepcopy(d1)
Matrix Computers (Page 4 of 5)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
d3[1][0]=10000 #This will not change in d1
3 dict.get(key,
default = "None") It is used to get the value specified for the passed key.
4 dict.setdefault(key,
default = "None") It is used to get the value specified for the passed key but it
will add the key in dict if not found.
5 dict.keys() It returns all the keys of the dictionary.
6 dict.values() It returns all the values of the dictionary.
7 dict.items() It returns all the key-value pairs as a tuple.
for key,value in d1.items():
print(key,value)
8 dict.update(dict2)
It updates the dictionary by adding the key-value pair of dict2
to this dictionary.
9 popItem() It will remove last item from the dictionary. It will give error if
dictionary is empty.
10 pop(key) It will remove the item having specified key from the
dictionary error if key not found. we can also use del
statement that will also give error if key not found.
11 fromkeys(keys,
value) It will add all keys in the dict with same value. If value is
missing then it will initialize all keys with None.
Remove all elements:-
d.clear() #It will not remove dictionary object
del d #It will remove dictionary object also
Reference Copy:-
d1=d
d is d1 #True
true copy:-
d1=d.copy()
d is d1 #False
How to access single element:-
print(d.get(1))
or
print(d[1])
Matrix Computers (Page 5 of 5)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
print(d[4]) #error if key not found
print(d.get(4)) #None if key not found
print(d.get(4,"Key not found")) #Key not found It will not add key 4 in
dictionary
default value:-
print(d.get(4)) #Return None if key not found and also add
this key in dict with None as its value
print(d.get(4,"D")) #Return D if key not found and also add this
key in dict with D in as its value
Difference between dict.get and dict.setdefault is that dict.get will never add new key in
dict but dict.setdefault add the key in dict if missing
display all keys:-
print(d.keys())
display all values:-
print(d.values())
display all key value pairs:-
print(d.items())
copy all keys of one dict into another dict:-
d1.update(d)
We can delete dictionary elements:-
del d["fees"]
or
d.pop("fees")
del d["due"] #key error
or
d.pop("due") #Key error
d.pop("due","key not found") #no error but returns key not found message
d.popitem() #remove last key value
creating dict with multiple keys but same values:-
d.fromkeys([1,2,3],"matrix")