1

I want to write a python dictionary in a string. The values of the items should be give by the formatted string.

I expected the following to work, but it doesnt because the first '{' used to define the dict is interpreted as a formated field

In: "{'key_1': '{value}'}".format(**{'value': 'test'})

the following works fine, but doesn't return the expected dict:

In: "'key_1': '{value}'".format(**{'value': 'test'})
Out: "'key_1': 'test'"

one way to overcome the problem is by using list brakets and replace them later by the dict brakets:

In: "['key_1': '{value}']".format(**{'value': 'test'}).replace('[', '{').replace(']', '}')
Out: "{'key_1': 'test'}"

How to write this in a better way?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Jacques
  • 13
  • 4

1 Answers1

0

Use double {{and }}:

 "{{'key_1': '{value}'}}".format(**{'value': 'test'})
Mike Müller
  • 82,630
  • 20
  • 166
  • 161