Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
27 views

Python Assignment 2

The document contains 5 Python programming exercises involving dictionaries: 1) Replace dictionary values in a string, 2) Sort a dictionary by values, 3) Count items in dictionary value lists, 4) Remove empty dictionary items, 5) Check for multiple dictionary keys.

Uploaded by

reyojiw404
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Python Assignment 2

The document contains 5 Python programming exercises involving dictionaries: 1) Replace dictionary values in a string, 2) Sort a dictionary by values, 3) Count items in dictionary value lists, 4) Remove empty dictionary items, 5) Check for multiple dictionary keys.

Uploaded by

reyojiw404
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Python Assignment 2

1. Write a Python program to Replace words from the dictionary

firstString = "Ammu BCA 2023 DSASC";


print("The string before replacing:", firstString)
thisdict = {
"BCA": "MCA",
"2023": "2025",
"DSASC": "BMSCE"
}
temp = firstString.split()
secondString = []
for word in temp:
secondString.append(thisdict.get(word,word))
secondString = ' '.join(secondString)
print("The string after replacing: ", secondString)
OUTPUT:
2. Write a program to sort dictionary by values (Ascending & Descending).

import operator
thisdict = { 'a': 91, 'b': 74, 'c': 11, 'd': 64, 'e': 0, 'f': 38, 'g': 9}
print("The original dictionary:", thisdict)
sorteddict = sorted(thisdict.items(), key=operator.itemgetter(1))
print("Ascending order:",sorteddict)
sorteddict = sorted(thisdict.items(), key=operator.itemgetter(1), reverse=True)
print("Descending order:",sorteddict)

OUTPUT:
3. Write a Python program to count number of items in a dictionary value
that is a list.

thisdict = {'a': [9,0,1,2,7,3], 'b': [5], 'c': [6,8], 'd': [4,11,5,3]}


count = sum(map(len, thisdict.values()))
print(count)

OUTPUT:
4. Drop empty Items from a given Dictionary

thisdict = {'Name': 'Ammu', 'Age': 21, 'DateOfBirth' : None, 'City': 'Bengaluru',


'BloodGroup': None, 'nationality': 'Indian'}
print("The original dictionary:",thisdict)
thisdict = {key: value for (key, value) in thisdict.items() if value is not None}
print("After dropping the empty items from the dictionary: ",thisdict)

OUTPUT:
5. Write a Python program to check multiple keys exists in a dictionary.

thisdict = {'name': 'Ammu', 'age': 21, 'program': 'MCA', 'semester': 1,


'section': 'A', 'college': 'BMSCE'}
print(thisdict.keys() >= {'name', 'semester', 'college'})
print(thisdict.keys() >= {'name', 'Ammu'})
print(thisdict.keys() >= {'college', 'BMSCE'})
print(thisdict.keys() >= {'program', 'semester', 'section'})

OUTPUT:
Output on Mozilla Firefox Uncropped:

You might also like