Search code examples
python-3.xpython-requestsformatpayloadf-string

Format string dict in dict


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?


Solution

  • 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}'}