Week 11 Python
Week 11 Python
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})
print('Before Deleting')
for key, value in od.items():
print(key, value)
# deleting element
od.pop('a')
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]})
OUTPUT:
ChainMap({'A': 1, 'B': 2, 'C': 4}, {'f': 2, 'e': 4, 'g': 6})