Dictionary Methods
Dictionary Methods
Methods/Functions
len( ) :
This function returns the length of Dictionary means, it returns the total number of Key-Value pairs
present in the dictionary.
for example:
OUTPUT
Length of dictionary A is : 3
Length of dictionary B is : 4
clear( ) :
This function simply removes all items from the dictionary. for example
OUTPUT
Length of dictionary A is : 0
Length of dictionary B is : 4
NOTE : This function only remove element/items from the dictionary. It does not delete the
dictionary
get( ) :
This function simply return the value of the required Key. for example
OUTPUT
Two
Cat
None
Key Not Found
OUTPUT
dict_items([(1, 'One'), (2, 'Two'), (3, 'Three')])
dict_items([('A', 'Apple'), ('B', 'Bat'), ('C', 'Cat'), ('D', 'Doll')])
keys( ) :
This function return all the keys of dictionary in the form of List. for example :
OUTPUT:
dict_keys([1, 2, 3])
dict_keys(['A', 'B', 'C', 'D'])
values( ):
This function return all the values of dictionary in the form of List. for example :
OUTPUT:
dict_values(['One', 'Two', 'Three'])
dict_values(['Apple', 'Bat', 'Cat', 'Doll'])
update( ):
This function merge the key value air of two dictionary into one. In simple words it simply
join/merge the two dictionary. It merge the keys and values of one dictionary into other and
overwrites the values of the same key. for example:
OUTPUT
#It over writes the values of same keys and add the values of different keys
pop( ):
This function not only delete the element of required key but also return the deleted value.
B = {1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
a=B.pop(2) #It returns the element of Key - 2
print(a)
print(B)
OUTPUT
OUTPUT
2 max() – returns key having maximum value Tv = {'a':100, 'b':1292, 'c' : 88}
Keymax = max(Tv, key=Tv.get)
print(Keymax)
OUTPUT-> b
3 min()- returns key having minimum value
4 sorted- sort by key or value dict1 = {'b':100, 'a':12, 'c' : 88}
y = sorted(dict1.items(), reverse=True)
OUTPUT-> [('b', 100), ('c', 88), ('a', 12)] print(y)