如何在python中打印字典的键和值

时间:2013-12-30 14:28:59

标签: python dictionary

这就是我所拥有的

prices={'banana':4,'apple':2,'orange':1.5,'pear':3}
stock={'banana':6,'apple':0,'orange':32,'pear':15}

我想按以下格式打印:

item
price: x
stock: x

4 个答案:

答案 0 :(得分:2)

迭代字典:产生密钥。使用键访问字典值的值。

prices={'banana':4,'apple':2,'orange':1.5,'pear':3}
stock={'banana':6,'apple':0,'orange':32,'pear':15}
for fruit in prices:
    print(fruit)
    print('price: {}'.format(prices[fruit]))
    print('stock: {}'.format(stock[fruit]))

输出:

orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
price: 2
stock: 0

答案 1 :(得分:2)

您可以执行以下操作:

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"

哪会产生:

orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
price: 2
stock: 0

但是我认为嵌套字典在这里更合适:

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']

答案 2 :(得分:1)

prices={'banana':4,'apple':2,'orange':1.5,'pear':3}
stock={'banana':6,'apple':0,'orange':32,'pear':15}

for item in prices:
    print item
    print "price: ",prices[item]
    print "stock: ",stock[item]  

答案 3 :(得分:1)

迭代一个词典中的键......

  for key in prices:
      print key
      print "price: %d" % prices[key]
      print "stock: %d" % stock[key]