![]() |
Help with dictionaries - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Help with dictionaries (/thread-16434.html) |
Help with dictionaries - erfanakbari1 - Feb-28-2019 Hey buddies , I just tried to work with Dictionaries in Python but I got stuck in trouble with it . # choose any name for the dictionary dictShopping = {'soap': '10' , 'bread': '5' , 'shampoo': '8'} dictSelling = {'soap': '20.50' , 'bread': '25.99' , 'shampoo': '80'} print(' The shopping center have {} quantities of bread which costs {} dollars . '.format(dictSelling,soap))I don't know to to get along with this code to make my program run as well . I just wanted to do these with my codes : .Display the item with quantity and the cost of item in a single line like The shop have 10 quantities of soap which cost 20.50 USD each. So I'll be very happy if you can help me with this . Thanks RE: Help with dictionaries - Larz60+ - Feb-28-2019 # choose any name for the dictionary dictShopping = {'soap': '10' , 'bread': '5' , 'shampoo': '8'} dictSelling = {'soap': '20.50' , 'bread': '25.99' , 'shampoo': '80'} print(' The shopping center have {} quantities of bread which costs {} dollars. '.format(dictShopping['soap'], dictSelling['soap'])) RE: Help with dictionaries - borrowedcarbon - Feb-28-2019 To get the value from a dictionary, use dict_name[key]. In your assignment, dictShopping['soap'] will return the value '10'. Using a variable named item allows easy switches of item name without reformatting the print string. # first string formatting option dictShopping = {'soap': '10', 'bread': '5', 'shampoo': '8'} dictSelling = {'soap': '20.50', 'bread': '25.99', 'shampoo': '80'} item = 'soap' print('The shopping center has {} quantities of bread which cost {} dollars each.'.format(dictShopping[item], dictSelling[item]))In case you are using python 3.6+, this version is better - it uses f strings instead of .format() # format string using f strings (python 3.6+) dictShopping = {'soap': '10', 'bread': '5', 'shampoo': '8'} dictSelling = {'soap': '20.50', 'bread': '25.99', 'shampoo': '80'} item = 'soap' print(f'The shopping center has {dictShopping[item]} quantities of bread which cost {dictSelling[item]} dollars each.') |