STUDY MAT XI Dictionary
STUDY MAT XI Dictionary
< dictionary-name> = { <key> : < value > , < key > : < value > .........}
Each entry consists of a pair < key : value > separated by a comma
For example
For example
>>> dict = { [1,2] : “sangeeta”}#error As the key has been given as list
Prepared by :Gajendra S Dhami,PGT CS,LPS south city
Initializing a Dictionary
1. To initialize a dictionary , give key : value pairs , separated by
commas and enclosed in curly braces .....
Result = { “ Abhai “ : 88 , “ Amit “ : 90 , “ Atul” : 95 , “ Deepti “ : 56 }
result=dict(name="amit",per=99)
>>> result
For example
result=dict(zip(("name","per","result"),("Ankita",99,"PASS")))
>>> result
For example
>>> monthday[“January”]
Python return... 31
Traversing a Dictionary
Traversing means accessing and processing each element of a dictionary. To
access each element of a dictionary we take help of Python loop as we do take in List
For example
Monthdays={“January”:31,”February”:28,” March”,31, “April” : 30 , “ May” :31 , “
June “ : 30 , “July “: 31 , “August “ : 31 , “ September “ : 30 , “ October “: 31 ,
“November “ : 30 , “ December” : 31 }
To see all the elements of the ab ove dictionary, we give the following loop
January : 31
Febraury : 28
March : 31
April : 30
.....
....
Decemeber : 31
In the above example month is the loop variable, which gets assigned with the keys
of monthdays dictionary , one at a time
>>> week.keys ( )
Will show
>>> week.values ( )
Will show
dict_values([1, 2])
one can also convert the sequence returned by keys ( ) and values ( ) functions by
using list ( ) as shown belo w :
[1 , 2 ]
result["totalmarks"]=499
>>> result
result["per"]=99.5
>>> result
1. To delete a dictionary element, one can use del command. The syntax for
doing so is as follows
del < dictionary > [ <key>]
For example
result={'name': 'Ankita', 'per': 99, 'result': 'PASS', 'totalmarks': 499}
>>> del result['result']
>>> result
{'name': 'Ankita', 'per': 99, 'totalmarks': 499}
For example
result={'name': 'Ankita', 'per': 99, 'result': 'PASS', 'totalmarks': 499}
>>> result.pop('per')
99
>>> result
{'name': 'Ankita', 'result': 'PASS', 'totalmarks': 499}
The not in operator will return true if the given key is not present in the
dictionary, otherwise false.
For example
result={'name': 'Ankita', 'result': 'PASS', 'totalmarks': 499}
False
True
1. len ( ) method
This method is used to tell the length i.e total number of elements present in to
the dictionary. The syntax to use len ( ) method is as follow :
len ( < dictionary> )
for example