python - Getting a key error while using a dict with TEMPLATE.format() -


at loss on this. i'm getting key error can't figure out why key referenced looks it's in 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 error got:

    report.append(template.format(stock)) keyerror: 'ticker' 

you need put ** in front of dictionary argument. so, last line be:

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

and should work.

so 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 pass dictionary str.format()


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -