It is a collection of key values. it allow us to store data in key-value pairs. we create a dictionary using bracket.
a={'a':1,'b':[5,7,9]}
dictionary key must be immutable such as tuples, string, integer. We can't use mutable object like list as key.
valid dictionary:
a={'a':1,('b','a'):[5,7,9]}
Invalid dictionary:
a={'a':1,['b','a']:[5,7,9]}
Length of dictionay:
a={'a':1,('b','a'):[5,7,9]}
len(a)
Access dictionary item:
We can access dictionary item using key inside bracket
a={'a':1,('b','a'):[5,7,9]}
a['a']
We can use get method to access dictionary:
a.get('a')
Difference between get and dict[key] method:
dict[key] returns error if the key value is wrong whereas get method doesn't return error.
We can add and change the value of dictionary:
add value
a['c']=3
change value:
a['c']=5
Remove dictionary items:
del a['a']
Dictionary Method:
a.clear(): It remove all item from list, also it doesn't return any value or doesn't take any parameter.
a.items(): Return list containing tuple for each key value pair.
a.keys(): Returns a list containing key dictionary keys.
a.pop(key): Removed the specified item from dictionary and return the value of key.
a.popitem(): Removed the item that was last inserted into dictionary.
a.values(): Return a list of all the values in the dictionary.
fromkeys(): This is a method which can use to create dictionaly from given key and values.
It takes two paramerter, key and values. key is mandatory and value is optional.
Example 1:
key={'a','b'}
value={1}
a=dict.fromkeys(key)
a
Example 2:
key={'a','b'}
value={1}
a=dict.fromkeys(key,value)
a
Note: The same value is assigned to all the key of dictionary.
From key with mutable object:
key={'a','b'}
value=[1]
a=dict.fromkeys(key,value)
a
value.append(2)
a
Dictionary Comprehension: It is a way to build dictionaries from an iterable.
Example 1
keys=['a','b','c','d','e']
v=[1,2,3,4,5]
d={k:v for (k,v) in zip(keys,v)}
d
Example 2
v=[1,2,3,4,5]
d={x:x**2 for x in v}
d
With conditional statement
v=[1,2,3,4,5]
d={x:x**2 for x in v if x**3%4==0}
d
Example 3
v=[1,2,3,4,5]
d={x:{x:x+i for i in v} for x in v}
d
SetDefault(): Return the value of key if the key is in dictioanry else it insert a key with the default value.
Example 1:
d={'a':1,'b':2,'c':5}
d.setdefault('b',9)
# b exist in dictionary so it will return value of b