Sort an Inventory List (Python)

vegaseat 1 Tallied Votes 574 Views Share

A common way to represent an inventory is with a list of tuples. Each tuple represents the item name and the item count. You can sort this inventory list by item name or item count. Here is an example to pick a sort key. It's your summer job to run a fruit stand along the road. You also have to count the grapes twice a day, the boss doesn't want you to eat any!

# sort an inventory list by item count
# Python24 (needed)  modified by  vegaseat  10may2005

import operator

# create an inventory list of tuples
# each tuple contains the item name and the count of the item
inventory = [('apple', 35),('grape', 967),('banana', 12),('pear', 5),('cumquat', 10)]

print '-'*50  # 50 dashes, cosmetic stuff
print "Original inventory list:"
print inventory
 
# establish the sort key
# each tuple is zero based
# item name = 0 and item count = 1
getcount = operator.itemgetter(1)

print "Inventory list sorted by item count:"
# now sort by item count
sortedInventory = sorted(inventory, key=getcount)
print sortedInventory

# more official look
print "Fruit inventory:"
for item in sortedInventory:
    print "%-10s%6d" % (item[0], item[1])