Python Collections: a) Write a Python program to show different ways
to create Counter.
Program:
from collections import Counter
print(Counter(['A','B','A','C','O','U','T','R','A']))#using list
print(Counter({'A':3,'B':3,'C':5}))#using dictionary
print(Counter(A=3,B=5,C=9))
OUTPUT:
Counter({'A': 3, 'B': 1, 'C': 1, 'O': 1, 'U': 1, 'T': 1, 'R': 1})
Counter({'C': 5, 'A': 3, 'B': 3})
Counter({'C': 9, 'B': 5, 'A': 3})
b) Write a Python program to demonstrate working of
OrderedDict
Program:
from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
print('Before Deleting')
for key, value in od.items():
print(key, value)
# deleting element
od.pop('a')
# Re-inserting the same
od['a'] = 1
print('\nAfter re-inserting')
for key, value in od.items():
print(key, value)
OUTPUT:
Before Deleting
a1
b2
c3
d4
After re-inserting
b2
c3
d4
a1
c) Write a Python program to demonstrate working of
defaultdict
Program:
from collections import defaultdict
d=defaultdict(list)
for i in range(10):
d[i].append(i)
print(d)
OUTPUT:
defaultdict(<class 'list'>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4], 5: [5], 6: [6], 7: [7], 8: [8],
9: [9]})
d) Write a python program to demonstrate working of
ChainMap
Program:
from collections import ChainMap
a={'A':1,'B':2,'C':4}
b={'f':2,'e':4,'g':6}
print(ChainMap(a,b))
OUTPUT:
ChainMap({'A': 1, 'B': 2, 'C': 4}, {'f': 2, 'e': 4, 'g': 6})