Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyError when using .format on a string in Python [duplicate]

Tags:

python

string

I have a string and I want to use .format function of python to add some variables in it on runtime, This is my string :

'{"auth": {"tenantName": "{Insert String Here}", "passwordCredentials": {"username": "{insert String here}", "password": "{insert String Here}"}}}'

when I use .format like this:

credentials='{"auth": {"tenantName": "{tenant}", "passwordCredentials": {"username": "{admin}", "password": "{password}"}}}'.format(tenant='me',admin='test',password='123')

It gives me the following error:

KeyError: '"auth"'

Any Help? Thanks in Advance.

like image 767
mobykhn Avatar asked Dec 19 '13 04:12

mobykhn


2 Answers

{ and } are special characters for string formatting, as you clearly are aware, since you are using them for {tenant}, {admin} and {password}. All the other {s and }s need to be escaped by doubling them. Try:

credentials='{{"auth": {{"tenantName": "{tenant}", "passwordCredentials": {{"username": "{admin}", "password": "{password}"}}}}}}'.format(tenant='me',admin='test',password='123')
like image 98
desired login Avatar answered Nov 14 '22 00:11

desired login


You are using the wrong tool for your trade. You are dealing with json, and you need to use the json library to parse your data and then access your field as a dictionary

>>> import json
>>> data_dict = json.loads(data)
>>> data_dict["auth"]["tenantName"]
u'{Insert String Here}'
like image 6
Abhijit Avatar answered Nov 14 '22 01:11

Abhijit