Introductions to Dictionaries
● A collection of items where each item is represented by a key-value pair
● Key and values are separated by :
● The elements are enclosed in { }
● d={key1:val1,key2:val2, key3:value3}
Example: d1={1:’A’, 2:’B’, 3:’C’}
● d2={‘name’:’ram’, ‘Rno’:72, ‘percentage’:72.5,’passed’:True}
How to create an empty dictionary
● Example:
d={ }
● Type(d): <class 'dict'>
Access the content of the dictionary
To access the elements of the dictionary, we should use a
key, not an index value.
Example:
d1={1:’A’, 2:’B’, 3:’C’}
d2={‘name’:’ram’,‘Rno’:72,‘percentage’:72.5,’passed’:Tr
ue}
d1[1]=‘A’
d1[2]=‘B’
d2[‘Rno’]=72
d2[‘passed’]=True
How to Add items to the dictionary
d1={1:’A’, 2:’B’, 3:’C’}
d1[4]=‘D’ #OUTPUT {1:’A’, 2:’B’, 3:’C’,4:’D’}
How to modify items of the dictionary
d1[1]=‘E’ # d1={1:’E’, 2:’B’ , 3:’C’}
How to delete items from the dictionary
del d1[1]
print[(d1)
Output: d1={ , 2:’B’, 3: ‘C’} # full dictionary delete del d1
Whether the dictionary is:
[Link] or ordered: The dictionary is an
unordered collection of items.
d1={1:’A’, 2:’B’, 3:’C’}
Print(d1) # any order you may get output
2. Mutable or immutable: Dictionary is mutable; we
can add new items in to the dictionary (keys-
>immutable, values-> mutable)
d1={1:’A’, 2:’B’, 3:’C’}
3. Unique or duplicate: keys are unique, values are
either unique or duplicates.
d1={1:’A’, 2:’B’, 3:’C’, 4:’A’}
●
● Aliasing and copying
● Dictionaries, like lists, are mutable objects.
● Aliasing happens when two variables point to the same dictionary in memory.
● Any modification made through one variable automatically affects the dictionary accessed through
the other variable.
● alias and opposites refer to the same object; copy refers to a fresh copy of the same dictionary. If
we modify alias, opposites is also changed: