Answer to Question #186790 in Python for desmond

Question #186790

Write a for loop that prints a dictionary's items in sorted (ascending) order


1
Expert's answer
2021-04-30T16:52:13-0400
#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=': ')

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS