1

At a loss on this. I'm getting a key error but I can't figure out why as the key referenced looks like it's in the dict.

Any help?

TEMPLATE = "{ticker:6s}:{shares:3d} x {price:8.2f} = {value:8.2f}"

report = []

stock = {'ticker': 'AAPL', 'price': 128.75, 'value': 2575.0, 'shares': 20}

report.append(TEMPLATE.format(stock))

This is the error I got:

    report.append(TEMPLATE.format(stock))
KeyError: 'ticker'
jkd
  • 1,045
  • 1
  • 11
  • 27
Daniel Dow
  • 487
  • 1
  • 7
  • 20

1 Answers1

3

You need to put ** in front of the dictionary argument. So, your last line would be:

report.append(TEMPLATE.format(**stock))

and it should work.

So your code should be:

TEMPLATE = "{ticker:6s}:{shares:3d} x {price:8.2f} = {value:8.2f}"

report = []

stock = {'ticker': 'AAPL', 'price': 128.75, 'value': 2575.0, 'shares': 20}

report.append(TEMPLATE.format(**stock))

Related: Python 3.2: How to pass a dictionary into str.format()

Community
  • 1
  • 1
jkd
  • 1,045
  • 1
  • 11
  • 27