Ryan113
Ryan113

Reputation: 686

I would like to print out a formatted dictionary in Python

I've been working on creating a store in Python. I would like to print out the dictionary I made that stores the items for the store, but by using a format I created by redefining __str__. Is there a way I could do this by creating a loop?

class Store():
def __init__(self):
    self.available_items = []
    self.customer_list = []


class Inventory():
    def __init__(self, name, stock, price):
        self.name = name
        self.stock = stock
        self.price = price

    def __str__(self):
        return 'Name: {0}, Stock: {1}, Price: {2}'.format(self.name, self.stock, self.price)


# Store name is listed along with its database of items
amazon = Store()

amazon.available_items = {
    111: Inventory('Ice Cubes', 10, 7.99),
    121: Inventory('Butter', 8, 4.99),
    131: Inventory('Radio', 70, 17.99),
    141: Inventory('Underwear', 15, 3.99),
    151: Inventory('Coffee', 17, 2.99)
    }


print(amazon.available_items[111])

for items in amazon.available_items:
    print items

Upvotes: 0

Views: 70

Answers (1)

MrAlexBailey
MrAlexBailey

Reputation: 5289

I believe you're trying to accomplish this:

for items in amazon.available_items:
    print(amazon.available_items[items])

Results in:

Name: Butter, Stock: 8, Price: 4.99
Name: Radio, Stock: 70, Price: 17.99
Name: Coffee, Stock: 17, Price: 2.99
Name: Underwear, Stock: 15, Price: 3.99
Name: Ice Cubes, Stock: 10, Price: 7.99

There is another way to loop over a dictionary which you may find useful for other implementations. You can separate the keys and values with iteritems():

for key, value in amazon.available_items.iteritems():
    print(value)

Through this loop you can access the 111, 121, 131... at the key variable, and Name: Butter.... at the value variable.

Upvotes: 2

Related Questions