Programming With Python Practical 9
Question 1
Write a Python script to sort (ascending and descending) a dictionary by value.
sort.py
my_dict = { 'num1': 6, 'num2': 3, 'num3': 2, 'num4': 4, 'num5': 1, 'num6': 5}
sortedVal = sorted(my_dict.values())
keys=[]
print("Dictionary in ascending order by values is: ")
for val in sortedVal:
for k,v in my_dict.items():
if(val==v):
keys.append(k)
sortedDict=dict(zip(keys,sortedVal))
print(sortedDict)
sortedVal.clear()
keys.clear()
sortedVal = sorted(my_dict.values(),reverse=True)
keys=[]
print("Dictionary in descending order by values is: ")
for val in sortedVal:
for k,v in my_dict.items():
if(val==v):
keys.append(k)
sortedDict=dict(zip(keys,sortedVal))
print(sortedDict)
Output

Question 2
Write a Python script to concatenate following dictionaries to create a new one.
Sample Dictionary:
dic1 = {1:10, 2:20}
dic2 = {3:30, 4:40}
dic3 = {5:50,6:60}
concat.py
d1 = {1: 10, 2: 20}
d2 = {3: 30, 4: 40}
d3 = {5: 50, 6: 60}
d4={}
d4.update(d1)
d4.update(d2)
d4.update(d3)
print("After concating dictionary is: ",d4)
Output

Question 3
Write a Python program to combine two dictionary adding values for common keys.
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
combine.py
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
for i in d1.keys():
for j in d2.keys():
if(i==j):
d2[i]=d2[i]+d1[i]
d1.update(d2)
print("Combined dictionary is: ",d1)
Output

Question 4
Write a Python program to print all unique values in a dictionary.
Sample Data: [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"},
{"VII":"S005"}, {"V":"S009"}, {"VIII":"S007"}]
unique.py
list = [{"V": "S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"}, {"VII": "S005"}, {"V": "S009"}, {"VIII": "S007"}]
s=set()
for i in list:
for d in i.values():
s.add(d)
print("Unique values are: ",s)
Output

Question 5
Write a Python program to find the highest 3 values in a dictionary
highest.py
my_dict = { 'a': 56, 'b': 13, 'c': 82, 'd': 74, 'e': 11, 'f': 30}
sortedDict = sorted(my_dict.values(),reverse=True)
print("Highest three values are: ")
for i in sortedDict[:3]:
print(i)
Output
