Write a for loop that prints a dictionary's items in sorted (ascending) order
#for example create an instance of the dictionary for tests
test_dict = {'A': 2, 'H': 15, 'Z': 12, 'I': 31, 'B': 4, 'Y': 15}
print(test_dict)
# create list with elements [key:value] of dictionary
test_dict_to_list = []
for key in test_dict:
test_dict_to_list.append([key,test_dict[key]])
# sort the list by first value or dictionary key
test_dict_to_list.sort()
print('the result of sorting ascending key')
for item in test_dict_to_list:
print(item[0],item[1],sep=': ')
# sort the list by second value or dictionary values
values_sort = sorted(test_dict_to_list, key=lambda x: x[1])
print('the result of sorting ascending values')
for item in values_sort:
print(item[0],item[1],sep=': ')
Comments
Leave a comment