0
bag_id = 'abcd'
result_str = "{'affiliate_details.affiliate_bag_id': '{bag_id}'}".format(bag_id)

I want the output result_str as "{'affiliate_details.affiliate_bag_id':'abcd' }"

It gives a key error - affiliate_details

I tried with unpacking them using **{'bag_id':'abcd'} in the format but it too gives the same result. I think its assuming the kwarg for affiliate_details but how do I deal with a nested one?

Also tried providing this but it gives same error

result_str = "{'affiliate_details.affiliate_bag_id': '{bag_id}'}".format(**{'affiliate_details':'affiliate_details', 'bag_id':'abcd'})

1 Answer 1

2

how can python know where to search for format placeholders?

You have to escape the curly braces you want as bare curly braces:

"{{'affiliate_details.affiliate_bag_id': '{bag_id}'}}".format(bag_id=bag_id)

maybe you'd better build a real dictionary and serialize it:

result_dict = {'affiliate_details.affiliate_bag_id': bag_id}

then:

str(result_dict)

or

json.dumps(result_dict)

(slight differences when using json, with None and booleans, but you can use indentation options)

Sign up to request clarification or add additional context in comments.

2 Comments

I was actually using JSONBender and wanted to try it out in a single statement rather than calling a function and dumping json. Thanks for your answer... :)
answer also applies to any third party json serializer/parser as well of course :)

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.