NIKHIL RANE NIKHIL RANE - 1 year ago 106
Python Question

Use .format with string dictonary

I want to use my dictionary parameter in my string
Here is my dictionary

a = {"first_name": "ABC", "last_name": "PQR"}

Following statement gives correct output


But I want following output

"{ Hello {first_name} {last_name}.}".format(**a)
>>> '{ Hello ABC PQR.}'

It gives keyerror

KeyError Traceback (most recent call last)
<ipython-input-50-84fc42fb81f2> in <module>()
----> 1 "{ Hello {first_name} {last_name}.}".format(**a)

KeyError: ' Hello {first_name} {last_name}'

Answer Source

You can enter literal braces by doubling them:

>>> a = {"first_name": "ABC", "last_name": "PQR"}
>>> "{{ Hello {first_name} {last_name}.}}".format(**a)
'{ Hello ABC PQR.}'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download