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,494
  • 4
  • 26
  • 41

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
  • 854,459
  • 170
  • 1,222
  • 1,395
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
  • 215,873
  • 14
  • 235
  • 294