0% found this document useful (0 votes)
7 views

Week 11 Python

Python programs

Uploaded by

fd54w4yvdg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Week 11 Python

Python programs

Uploaded by

fd54w4yvdg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

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})

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy