Chapter 7
Chapter 7
Dictionary
Dictionaries are mutable unordered collections with elements in the
form of a key : value pairs.
We can change dictionary elements.
It can contain values of mixed datatypes.
Creating dictionary
Dictionaries are formed by placing key :value pairs
Ex:- {1:’a’,2:’b’,3:’c’}
{‘Name’: ’asha’,’age’:17}
# keys of a dictionary must be of immutable types
The curly brackets mark the beginning and end of the dictionary.
Each entry(key:Value)consists of a pair separated by a colon—
the key and corresponding value is given by writing colon(
between them,
The key –value pairs are separated by commas(,).
rno=[ ]
Enter Roll No., Marks :1, 67.5
mks=[ ]
Enter Roll No., Marks :2, 45.6
for a in range(4 ):
Enter Roll No., Marks :3, 78.4
r, m=eval (input(“Enter Roll No., Marks:”))
Enter Roll No.,Marks:4,70.5
rno.append(r)
Created dictionary
mks.append(m)
{1: 67.5, 2: 45.6, 3:78.4, 4:70.5}
d={rno[ 0]:mks[0],rno[1]:mks[1], rno[2]:mks[2], rno[3]:mks[3]}
print(“Created dictionary”)
print(d)
While accessing elements from a dictionary , we need key .(but in list , the
elements are accessed through their index)
In dictionaries, the elements are accessed through the keys defined in the
key:value pairs,
As per the syntax shown below:
Lookup:-A dictionary operation that takes a key and finds the corresponding value, is
called lookup
Eg
>>> d={“Vowell”:”a”,”Vowel12”:”e”,”Vowel13”:”I”,”Vowel4”:”o”,”Vowel5”:”u”}
>>>d[“Vowel1”]
>>>d[“Vowel4”]
Notice that keys given here are in quotation marks i.e are of string type.
‘o’
“Traversing a Dictionary”
D = {1:’a’,2:’b’,3:’c’}
for x in D
print(x,’ : ’,D[x])
Output :- 1 : ‘a’
2 : ‘b’
3 : ‘c’
Accessing Keys or Values Simultaneously
>>>
d={“Vowell”:”a”,”Vowel2”:”e”,”Vowel3”:”I”,”Vowel4”:”o”,”Vowel5”:”u”}
>>>d.keys( )
dict_keys([‘Vowel5’,’Vowel4’,’Vowel3’,’Vowel2’,’Vowel1’])
>>>d.values( )
Dict_values([‘u’,’o’,’I’,’e’,’a’])
[‘u’,’o’,’i’,’e’,’a’]
Characteristics of a dictionary
Unordered Set
A dictionary is a unordered set of Key:value pairs.
We can not tell the order or position of Key:Value pairs in a
dictionary as there is no index associated.
Not a sequence
Unlike a string, list and tuple, a dictionary is not a sequence
because it is unordered set of element.
The sequences are indexed by a range of ordinal numbers.
Hence , they are ordered , but a dictionary is an unordered
collection.
Indexed by Keys, Not Numbers
Keys must be Unique
Each of the Keys within a dictionary must be unique.
Keys are used to identify values in a dictionary, there cannot be
duplicate keys in a dictionary.
D= dict(zip((1,2,3),(‘a’,’b’,’c’)))
D => {1:’a’, 2:’b’, 3:’c’}
(iv) Initializing a Dictionary
Nesting Dictionaries
We can even add dictionaries as Values inside a dictionary.
We can store a dictionary as a value only, inside a dictionary.
Eg .
Employees={‘John’:{‘age’:25,’salary’:20000},’Diya’:{‘age’:35,’Salary’:50,000}}
print(‘Age:’, str(Employees[key][‘age’]))
print(‘Salary:’,str(Employees[key][‘salary]))
Output
Employee John:
Age : 25
Salary: 20,000
Employee Diya:
Age : 35
Salary: 50,000
In Dictionaries , the updation and addition of elements are similar in syntax. But for
addition, the key must not exist in the dictionary and for updation, the key must exist
in the dictionary.
Deleting Elements from a Dictionary
del D[2]
OR
D.pop( 2)
The in and not in operator check for membership only in keys of the dictionary
and not in values.
import json
print(jsob.dumps(D, indent=2) )
“1” : ‘a’,
“2” : ‘b’,
“3” : ‘c’
len(D) => 3
D.clear( )
D => {}
Dict() :- this function is used to create a new dictionary from iterables and other
dictionaries. Passing
Eg
Dict(iterable)
Eg data=[[1,67.8],[2,75.5],[3,72.5]]
D1=dict(data)
Print(“Created dictionary is “)
Print(d1)
UPDATE( ) method :-
The update( ) method merges key:value pairs from the new dictionary into the
original dictionary, adding or replacing as needed.
The items in the new dictionary are added to the old one and override any
items already there with the same keys.
D[2] = 10
get( ) :- It gets the value with the given key from the dictionary.
for x in lis :
print (x)
Output :- (1,’a’)
(2,’b’)
(3,’c’)