我想用Python打印出格式化的字典

时间:2015-03-03 20:15:39

标签: python dictionary

我一直在努力用Python创建商店。我想打印出我为商店存储商品的字典,但是使用我通过重新定义__str__创建的格式。有没有办法通过创建循环来做到这一点?

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

1 个答案:

答案 0 :(得分:2)

我相信你正在努力实现这一目标:

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

结果:

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

还有另一种循环字典的方法,您可能会发现它对其他实现很有用。您可以使用iteritems()

分隔键和值
for key, value in amazon.available_items.iteritems():
    print(value)

通过此循环,您可以访问111, 121, 131...变量的keyName: Butter....变量的value