Your best option will be to create a simple data structure to model what you have. Then you can store these objects in a simple list and sort/retrieve them any way you wish.
For this case, I'd use the following class:
class Fruit:
def __init__(self, name, color, quantity):
self.name = name
self.color = color
self.quantity = quantity
def __str__(self):
return "Name: %s, Color: %s, Quantity: %s" % \
(self.name, self.color, self.quantity)
Then you can simply construct "Fruit" instances and add them to a list, as shown in the following manner:
fruit1 = Fruit("apple", "red", 12)
fruit2 = Fruit("pear", "green", 22)
fruit3 = Fruit("banana", "yellow", 32)
fruits = [fruit3, fruit2, fruit1]
The simple list fruits
will be much easier, less confusing, and better-maintained.
Some examples of use:
All outputs below is the result after running the given code snippet followed by:
for fruit in fruits:
print fruit
Unsorted list:
Displays:
Name: banana, Color: yellow, Quantity: 32
Name: pear, Color: green, Quantity: 22
Name: apple, Color: red, Quantity: 12
Sorted alphabetically by name:
fruits.sort(key=lambda x: x.name.lower())
Displays:
Name: apple, Color: red, Quantity: 12
Name: banana, Color: yellow, Quantity: 32
Name: pear, Color: green, Quantity: 22
Sorted by quantity:
fruits.sort(key=lambda x: x.quantity)
Displays:
Name: apple, Color: red, Quantity: 12
Name: pear, Color: green, Quantity: 22
Name: banana, Color: yellow, Quantity: 32
Where color == red:
red_fruit = filter(lambda f: f.color == "red", fruits)
Displays:
Name: apple, Color: red, Quantity: 12