replacing json values dynamically using .format()

Viewed 94

i want to replace json value using format()

x = ['a','b']
y = ['x','y']

i wanted to pass payload dynamically to the APIs via iterating in the list items

for i in x:
    for j in y:
        "{'id': '{}', 'head': 10, 'tail': 0, 'rmc': '{}'}".format(i,j)  

  

so that output of payload would be like this

payload = {'id': 'a', 'head': 10, 'tail': 0, 'rmc': 'x'}
payload = {'id': 'a', 'head': 10, 'tail': 0, 'rmc': 'y'}
payload = {'id': 'b', 'head': 10, 'tail': 0, 'rmc': 'x'}
payload = {'id': 'b', 'head': 10, 'tail': 0, 'rmc': 'y'}

but while performing the above task i am getting the error is there any workaround for this or any other alternate?

1 Answers

You need to escape the braces:

x = ['a', 'b']
y = ['x', 'y']

for i in x:
    for j in y:
        print("{{'id': '{}', 'head': 10, 'tail': 0, 'rmc': '{}'}}".format(i, j))

Output

{'id': 'a', 'head': 10, 'tail': 0, 'rmc': 'x'}
{'id': 'a', 'head': 10, 'tail': 0, 'rmc': 'y'}
{'id': 'b', 'head': 10, 'tail': 0, 'rmc': 'x'}
{'id': 'b', 'head': 10, 'tail': 0, 'rmc': 'y'}
Related