0

I am trying to print a dictionary values

sales_record = {
'price': 3.24,
'num_items': 4,
'person': 'xyz'}

sales_statement = 'sales_record['person'] got sales_record['num_items'] item(s) at a cost of sales_record['price']each for a total of sales_record['price']*sales_record['num_items']'

print(sales_statement)

But this is simply giving me error

 File "<ipython-input-48-9c532ca6dcd1>", line 6
    sales_statement = 'sales_record['person'] got sales_record['num_items'] item(s) at a cost of sales_record['price']each for a total of sales_record['price']*sales_record['num_items']'
0

4 Answers 4

2

If you are using a recent version of Python (3.6 or newer), replace that line with:

sales_statement = f"{sales_record['person']} got {sales_record['num_items']} item(s) at a cost of {sales_record['price']} each for a total of {sales_record['price']*sales_record['num_items']}"
Sign up to request clarification or add additional context in comments.

Comments

1

You need to format your string. This will work for new and older versions of Python:

sales_statement = "{} got {} item(s) at a cost of {} each for a total of {}".format(sales_record['person'], sales_record['num_items'], sales_record['price'], sales_record['price'] * sales_record['num_items'])

Comments

0

It is basically because of the quotes.

sales_statement = str(sales_record['person']) + " got " + str(sales_record['num_items']) + " item(s) at a cost of " + str(sales_record['price']) + " each for a total of " +  str(sales_record['price']*sales_record['num_items'])

Comments

0

You can use double quotes for the full string and single quotes for the dictionary keys so that there is no confusion between them. In Python 3.6 or later. you can use f-strings and enclose the variables in curly braces, by preceding the string with the letter f. Prior to that you would have used the format string method.

sales_record = {
    'price': 3.24,
    'num_items': 4,
    'person': 'xyz'
}

sales_statement = f"{sales_record['person']} got {sales_record['num_items']} item(s) " \
                + f"at a cost of {sales_record['price']} each for a total of " \
                + f"{sales_record['price'] * sales_record['num_items']}"

print(sales_statement)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.