Home > Net >  Format string dict in dict
Format string dict in dict

Time:04-13

I want to have define a payload with variables, and the payload contains a dict inside a dict, like so:

payload = {"columns": "{x,y,z}",
           "number": "{n:123456}"}

I wanted ideally something like for a variable:

myVar = 123

payload = {"columns": "{x,y,z}",
           "number": "{n:{myVar}}"}

However this and other combinations doesn't work. I've tried both f-strings and formats. What is the best approach for this?

CodePudding user response:

You can do:

myVar = 123

payload = {"columns": "{x,y,z}", "number": f"{{n:{myVar}}}"}
print(payload)

Or:

payload = {"columns": "{x,y,z}", "number": "{n:"   str(myVar)   "}"}
print(payload)

Or:

payload = {"columns": "{x,y,z}", "number": "{{n:{}}}".format(myVar)}
print(payload)

All prints:

{'columns': '{x,y,z}', 'number': '{n:123}'}
  • Related