Edgar Aroutiounian Edgar Aroutiounian - 1 year ago 69
Python Question

Python - Printing String of Key in a Dict

My code is the following,

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

print("price :" + str(prices.values))
print("stock :" + str(stock.values))

I don't understand why I'm getting a spit out that looks as if I asked for the type. What gives?

Actually, my code logic is wrong.

I want the code to spit out the following

price : values
stock : values

For Example, this is how it should look

price: 2
stock: 0

Answer Source
prices = {'banana':'4', 'apple':'2', 'pear':'3'}
stock = {'banana':6, 'orange':32, 'pear':15}
for item in (prices.keys() & stock.keys()):
    print (item,"price:",prices.get(item,'-'),"stock:",stock.get(item,0))


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

Using get with a default will help if the stock and prices dictionaries contain different friuts ('keys') in each. The .get() function really helps here.

As mentioned by mgilson the following line is where the full set of fruit is created.

prices.keys() & stock.keys()  #{'orange', 'pear', 'banana', 'apple'}

I've also done this using set before


But I prefer the & approach.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download