0

I have an assignment in which a series of items and the amount a store carries of that item is given which I then have to put into a dictionary and display with the highest amount of stock to the lowest amount of stock. The dictionary looks a bit like this:

items = {'socks': 10, 'hammers': 33, 'keyboards': 56}

and the output would look like this:

keyboards: 56
hammers: 33
socks: 10

After getting the dictionary set up, I'm having difficulty with the second part... does anyone know how I could sort by value?

Raceimaztion
  • 9,204
  • 4
  • 25
  • 40

2 Answers2

1

It's easy to make a sorted list of (key, value) pairs:

import operator

slop = sorted(thelist.items(), key=operator.itemgetter(1), reverse=True)

and then you can loop over it to display it, e.g in Python 2:

for k, v in slop:
    print '{}: {}'.format(k, v),
print
Alex Martelli
  • 811,175
  • 162
  • 1,198
  • 1,373
1

To sort you can use sorted method:

items = {'socks': 10, 'hammers': 33, 'keyboards': 56}

sorted_items = sorted(items.items(), key=lambda v:  v[1], reverse = True)

As a key you specify to sort by value in the items dict. And to print it, you can just use:

for k,v in sorted_items:
    print("{}:{}".format(k,v))
Marcin
  • 168,023
  • 10
  • 140
  • 197