0

I need to print a python dictionary that is sorted by values. To sort the dictionary I used this code:

from operator import itemgetter
print(sorted(d.items(), key=itemgetter(1)))

The dictionary is well sorted, but the output is something like this:

[('Apple', '1'), ('Pears', '2'), ('Bananas', '3')]

I'd prefer:

Apple : 1
Pears : 2
Bananas : 3

I tried this wrong code:

dSorted = sorted(d.items(), key=itemgetter(1))
for i in dSorted:
    print(i + " : "+ dSorted[i])

How can I get this result? And, to understand better, when I use (sorted(d.items(), key=itemgetter(1))) the result is no longer a dictionary, but a different data structure, right?

martineau
  • 119,623
  • 25
  • 170
  • 301
Lorenzo
  • 107
  • 1
  • 5

2 Answers2

1

You are iterating a tuple of lists. So just iterate the keys and values and print as you want

dSorted = sorted(d.items(), key=itemgetter(1))
for key,value in dSorted:
        print(key + " : "+ value)
tomgalpin
  • 1,943
  • 1
  • 4
  • 12
-1

I am assuming you are using a recent version of python (in which dictionaries keep the order), if so, just make another dict out of the sorted list.

sorted_dict = dict(sorted(d.items(), key=itemgetter(1)))
print(sorted_dict)
alec_djinn
  • 10,104
  • 8
  • 46
  • 71