python怎么打印字典_如何用python打印字典的键和值

你可以这样做:prices = {'banana': 4, 'apple': 2, 'orange': 1.5, 'pear': 3}

stock = {'banana': 6, 'apple': 0, 'orange': 32, 'pear': 15}

for key in prices:

print key

print "price: %s" % prices[key]

try:

print "stock: %s" % stock[key]

except KeyError:

print "stock: KeyError"

会产生:

^{pr2}$

不过,我认为嵌套字典在这里更合适:items = {'banana': {'price': 4, 'stock': 6 },

'apple': {'price': 2, 'stock': 0 },

'orange': {'price': 1.5, 'stock': 32},

'pear': {'price': 3, 'stock': 15},

}

for key in items:

print key

print "price: %s" % items[key]['price']

print "stock: %s" % items[key]['stock']

你可能感兴趣的:(python怎么打印字典)