[go: up one dir, main page]

0% found this document useful (0 votes)
6 views4 pages

Program to Execute in Lab

The document outlines a series of Python programming exercises focused on dictionary operations. Key tasks include creating, modifying, and accessing dictionary elements, as well as performing operations like summing values, sorting, comparing, and deleting entries. Additional exercises involve nested dictionaries, pretty printing, and generating word frequency counts from sentences.

Uploaded by

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

Program to Execute in Lab

The document outlines a series of Python programming exercises focused on dictionary operations. Key tasks include creating, modifying, and accessing dictionary elements, as well as performing operations like summing values, sorting, comparing, and deleting entries. Additional exercises involve nested dictionaries, pretty printing, and generating word frequency counts from sentences.

Uploaded by

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

Program to execute in Lab

1. Write a program to create a dictionary to store birthday of a person.And accept


a name from the user if exists in the dictionary display his/her birthday
otherwise add it to the dictionary a new element
birthdays={'Alice':'Apr 1','Bob':'Dec 12','Carol':'Mar 4'}
while True:
print('Enter a name:(blank to quit)')
name=input()
if name=="":
break
if name in birthdays:
print(birthdays[name]+' is the birthday of '+name)
else:
print('I do not have birthday information for '+name)
print('When is their birthday?')
bday=input()
birthdays[name]=bday
print("Birthday database updated")
print(birthdays)

2. Write a program to sum all the values of a dictionary. Hint dict1 = {‘key 1’: 200,
‘key 2’: 300} Result: 500
dict1 = {'key 1': 200, 'key 2': 300}
total_sum = sum(dict1.values())
print("Result:", total_sum)

3. Write a Python program to sort dictionaries by values (Ascending/ Descending).


Given d = {‘key 1’: 2, ‘key 2’: 3, ‘key 3’: 4}
Ascending: [(‘key 1’, 2), (‘key 2’, 3), (‘key 3’, 4)]
Descending: [(‘key 3’, 4), (‘key 2’, 3), (‘key 1’, 2)]
d = {'key 1': 2, 'key 2': 3, 'key 3': 4}
ascending = sorted(d.items(), key=lambda item: item[1])
print("Ascending:", ascending)

# Sort in descending order


descending = sorted(d.items(), key=lambda item: item[1], reverse=True)
print("Descending:", descending)

4. Write a program to create and access dictionary elements


capital = {}
capital = { 'TamilNadu':'Chennai',
'Kerala':'Thiruvananthapuram',
'Karnataka':'Bengaluru',
'Andra Pradesh':'Hyderabad'
}
print("The capital city of Karnataka is",capital['Karnataka'])
5. Write a Program to compare two or more dictionary elements
dict1 = {'a':1,'b':2,'c':3}
dict2 = {'a':1,'b':2}
print(dict1==dict2)
dict1 = {'a':1,'b':2,'c':3}
dict2 = {'a':1,'b':5,'c':6}
print(dict1==dict2)
dict1 = {'a':1,'b':2,'c':3}
dict2 = {'a':1,'b':2,'c':3}
print(dict1==dict2)

6. Write a Program to delete operations on dictionary


capital1 = { }
capital2 = { }
capital1 = { 'TamilNadu':'Chennai',
'Kerala':'Thiruvananthapuram',
'Karnataka':'Bengaluru',
'Andra Pradesh':'Hyderabad'
}
capital2 = { 'Punjab':'Chandigarh',
'Rajasthan':'Jaipur',
'West Bengal':'Kolkata',
'Odisha':'Bhubaneswar'
}
print(capital1)
print(capital2)
del capital1['Andra Pradesh']
print(capital1)

7. Write a Program to assign multiple values to dictionaries using a list


capitals = { }
capitals = {'Andra Pradesh':['Hyderbad','Amaravathi']}
for val in capitals['Andra Pradesh']:
print(val)

8. Write a Program to modify a dictionary by new value or a new key-valuepair


capital = { }
capital = { 'TamilNadu':'Chennai',
'Kerala':'Thiruvananthapuram',
'Karnataka':'Bengaluru',
'Andra Pradesh':'Hyderabad'
}
capital['Andra Pradesh']='Amaravati'
capital['Assam'] = 'Dispur'
print(capital)
print("The new capital of AndraPradesh is",capital['Andra Pradesh'])
print("The capital city of Assam is",capital['Assam'])

9. Write a program to demonstrate the concept of nested dictionaries


family = { "child1" : { "name" : "Ram", "year" : 2004 },
"child2" : { "name" : "Laksman", "year" : 2007 },
"child3" : { "name" : "Bharath", "year" : 2011 }
}
print(family)
print(family["child2"]["name"])

10. Write a program to demonstrate the concept of nested dictionaries


allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
'Bob': {'ham sandwiches': 3, 'apples': 2},
'Carol': {'cups': 3, 'apple pies': 1}}

def totalBrought(guests, item):


numBrought = 0
for k, v in guests.items():
numBrought = numBrought + v.get(item, 0)
return numBrought

print('Number of things being brought:')


print(' - Apples ' + str(totalBrought(allGuests, 'apples')))
print(' - Cups ' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))

11. Write a program to demonstrate the concept of pretty printing using dictionaries
import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = { }
for char in message:
count.setdefault(char,0)
count[char] = count[char]+1
pprint.pprint(count)

12. program to create a dictionary conisisting of state & their corresponding dishes.
The program should accept a state name from a user and generate the
corresponding dishes for Eg- Punjab-->Aloo Paratha, Pujabi Lassi Karnataka
--> Jowar Roti, Bisi belebath maharastra--> Pav bhaji, vada pav gujarat-->
Dhokla, Khandvi
st_dish = { }
flag = False
ans = 'y'
while ans == 'y':
s = input("Enter the state:")
n = int(input("Enter the Number of dishes:"))
dishes = list()
print("Enter the dishes:")
for i in range(0,n):
dishes.append(input())
st_dish[s] = dishes
ans = input("please enter q to quit and y to continue")
print("State", "\t", "Dishes")
for s, dish in st_dish.items():
print(s, "\t",dish)
state = input("Enter the state whose dishes you want:")
for s, dish in st_dish.items():
if s == state:
flag= True
print(s,"\t",dish)
if flag == False:
print("The state ",state,"is not there:")

13. Program to accept a sentence and generate the frequency of words using
dictionaries
sent = input("Enter a sentence:").lower()
word = sent.split()
freq = {}
for w in word:
freq[w] = freq.get(w,0) + 1
k = freq.keys()
print("Frequency List")
print("--------------------")
for key in k:
print("%s: %d" %(key,freq[key]))

You might also like