-2

for example I have this Dictionary

a = {'Sara': 3, 'Marie': 1, 'James': 1, 'Alex': 1} I know that I can print the (key,value) one by one with such this code:

for key,value in a.items():
print(key,value)

and the result would be something like this:

Sara 3
Marie 1
James 1
Alex 1

My Question is how can I reserve this order to :

Alex 1
James 1
Marie 1
Sara 3
Brave120
  • 11
  • 1

2 Answers2

0
for key,value in list(a.items())[::-1]:
    print(key,value)

Convert that a.items() into a list and then switch the order by adding [::-1]

0
a = {'Sara': 3, 'Marie': 1, 'James': 1, 'Alex': 1} 
sort_a= sorted(a.items(), key=lambda x: x[1], reverse=False)
for i in sort_a:
   print(i[0],i[1])

Try this

alexiao
  • 36
  • 3