Sorting by value in a python dictionary?
Question: 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?


Answer: 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
    

