Assignment Based on Dictionary
Assignment Based on Dictionary
DICTIONARY METHODS
clear() Removes all the elements from the dictionary
rainfall={'SUNDAY':3.4,'MONDAY':5.2,'TUESDAY':1.7,'WEDN
ESDAY':0.0,'THURSDAY':0.15,'FRIDAY':4.0,'SATURDAY':1.2}
key=str(input("Enter key to check:"))
if key in rainfall.keys():
print("Key is present and value of the key is:")
print(rainfall[key])
else:
print("Key isn't present!")
2. Write a program to remove the given key from a dictionary
railfall={‘SUNDAY’:3.4,’MONDAY’:5.6,’TUESDAY’:4.2,’WEDNESDAY’:1.0,’TH
URSDAY’:0.0,’FRIDAY’:2.5,’SATURDAY’:3.1}
rainfall={'SUNDAY':3.4,'MONDAY':5.2,'TUESDAY':1.7,'WEDN
ESDAY':0.0,'THURSDAY':0.15,'FRIDAY':4.0,'SATURDAY':1.2}
print("Initial dictionary")
print(rainfall)
key=input("Enter the key to delete:")
if key in rainfall:
del rainfall[key]
else:
print("Key not found!")
print("Updated dictionary")
print(rainfall)
3. Write a program to input two list from user and form a dictionary using
its elements as key and values.
keys=[]
values=[]
n=int(input("Enter number of elements for dictionary:"))
print("For keys:")
for x in range(0,n):
element=input("Enter element" + str(x+1) + ":")
keys.append(element)
print("For values:")
for x in range(0,n):
element=input("Enter element" + str(x+1) + ":")
values.append(element)
d=dict(zip(keys,values))
print("The dictionary is:")
print(d)
4. Write a program to convert a number entered by the user into its corresponding number in
words. For example, if the input is 876 then the output should be 'Eight Seven Six'.
(Hint. use dictionary for keys 0-9 and their values as equivalent words.)
Solution
digit = 0
str = ""
digit = num % 10
num = num // 10
print(str)
5. Create a dictionary whose keys are month names and whose values are the number of
days in the corresponding months.
(a) Ask the user to enter a month name and use the dictionary to tell how many days are in
the month.
(d) Print out the (key-value) pairs sorted by the number of days in each month.
Solution
days_in_months = {
"january":31,
"february":28,
"march":31,
"april":30,
"may":31,
"june":30,
"july":31,
"august":31,
"september":30,
"october":31,
"november":30,
"december":31
if m not in days_in_months:
else:
for i in days_in_months:
if days_in_months[i] == 31:
day_month_lst = []
for i in days_in_months:
day_month_lst.append([days_in_months[i], i])
day_month_lst.sort()
month_day_lst =[]
for i in day_month_lst:
month_day_lst.append([i[1], i[0]])
sorted_days_in_months = dict(month_day_lst)
print()