1.Use a for loop and the list append method to generate the powers of 2 to produce the following result [1, 2, 4, 8, 16, 32, 64, 128]
2.Write a for loop that prints a dictionary's items in sorted (ascending) order
Question 1:
lst = []
for i in range(8):
x = (2**i)
lst.append(x)
print(lst)
Question 2:
import operator
# dictionary
d = {1: 3, 3: 2, 4: 1, 2: 3, 0: 0}
# sorting
sorted_d = sorted(d.items(), key=operator.itemgetter(1))
# printing sorted dict.
print('Dictionary in ascending order by value : ',sorted_d)
Comments
Leave a comment