how to print the keys and values ​​of a dictionary in python

advertisements

This is what I have

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

I want to print it in following format:

item
price: x
stock: x


You could do something like:

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"

Which would yield:

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


However I think a nested dictionary would be more appropriate here:

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