0

I am learning python coding and wanted to get some help with sorting dictionary. Based on information available on the internet, I was able to figure out how to sort a dictionary by keys and by values. However, I am having trouble trying to find a way to sort and print the key, value pair if i sort by values. Here's my code:

fish = {'Chicago':300, 'San Francisco':200, 'Dallas':450, 'Seattle': 325, 'New York City': 800, 'Los Angeles':700, 'San Diego':650}
for i in sorted(fish): print (i, fish[i])

#The above loop will print the items from the dictionary in sorted order of keys.

for i in sorted(fish.items()): print (i)
#The above loop will print the items in sorted order of keys. It will print as a tuple.

for i in sorted(fish.values()): print (i)
#The above loop will print the items in sorted order by values.

#end of code

Is there a way to print the list of key value pairs from a dictionary in sorted order of values.

My result should be

  • San Francisco 200
  • Chicago 300
  • Seattle 325
  • Dallas 450
  • San Diego 650
  • Los Angeles 700
  • New York City 800

One of the way to do this is:

def by_value(item): return item[1]
for k, v in sorted(fish.items(), key=by_value): print (k,v)

I don't want to define a function. I want a for loop with sorted command. Is there any? I am not sure if a lambda function will do this. I haven't tried it. That's my next step.

stackoverflow provided me a response. Looks like this was asked and answered. So cool.

How do I sort a dictionary by value?

Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33

1 Answers1

3

Sort using value by lambda:

sorted(fish.items(), key=lambda k: k[1])

To print key and values in sorted order of values.

for k, v in sorted(fish.items(), key=lambda k: k[1]):
    print(k)
    print(v)
Astik Anand
  • 12,757
  • 9
  • 41
  • 51