Professional Documents
Culture Documents
Assignment # 5
Assignment # 5
Assignment # 5
#5
1.Write a Python program to generate a dictionary that contains numbers (x)
(between 1 and n) as the keys and x*x as their corresponding value. ( the
dictionary should be of the form {x :x*x ,.....} where x ranges from 1 to n.
Code:
d={}
n=eval(input("Enter a number:"))
for i in range(1,n+1):
d[i]=i*i
print(d)
Output:
Enter a number:8
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
>>>
2.Write a Python Program to create a Dictionary with Key as First Character and
Value as count of the Words Starting with that Character (the words have to be
input by the user) as long as the user wants.
Example, if the user input is Hello, Bye, Good,Great
{'H':1,"B":1,"G":2}
Code:
d = {}
a = input("Enter a string: ")
s = a.title()
for i in s.split():
d[i[0]] = s.count[i[0]]
print(d)
Output:
Enter a string: hello, bye, good, great
{'H': 1, 'B': 1, 'G': 2}
>>>
3.Write a program to input a string and then count and store the frequency of each
character of the string in a dictionary.
Code:
d={}
s=input("Enter a string: ")
for i in s:
d[i]=s.count(i)
print(d)
Output:
Enter a string: hello,bye,great,good
{'h': 1, 'e': 3, 'l': 2, 'o': 3, ',': 3, 'b': 1, 'y': 1, 'g': 2, 'r': 1, 'a': 1, 't': 1, 'd': 1}
>>>
4.Write a program to create a dictionary PRODUCT with the keys:
Code:
Month_Days={}
Month_Name=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov',
'Dec']
Number_Days=[31,28,31,30,31,30,31,31,30,31,30,31]
for i in range(len(Month_Name)):
Month_Days[Month_Name[i]]=Number_Days[i]
print(Month_Days)
Output:
{'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30, 'Jul': 31, 'Aug': 31,
'Sep': 30, 'Oct': 31, 'Nov': 30, 'Dec': 31}
>>>
6. Write a program to create a dictionary which adds the values of the common
keys from the dictionaries D1 and D2 mentioned below:
D1 = {'A1':10,'A2':40,'A3':60}
D2 = {'A1':20,'A2':40}
D3 = {'A1':30,'A2':80,'A3':60}
Code:
d1=eval(input("Enter the first dictionary: "))
d2=eval(input("Enter the second dictionary: "))
d3={}
if len(d1)>len(d2):
for i in d1.keys():
if i in d2.keys():
d3[i]=(d1[i]+d2[i])
else:
d3[i]=d1[i]
else:
for i in d2.keys():
if i in d1.keys():
d3[i]=(d2[i]+d1[i])
else:
d3[i]=d2[i]
print("D3:",d3)
Output:
Enter the first dictionary: {'A1':10,'A2':40,'A3':60}
Enter the second dictionary: {'A1':20,'A2':40}
D3: {'A1': 30, 'A2': 80, 'A3': 60}
>>>