-1

I have a python variable containing the string A and another one containing the string B.

I want to generate the string which represents the dictionary containing the aforementioned two strings as a key value pair. How can I do it? Using nested curly brackets inside a string literal seems not to work. But I need that notation to use .format()

>>> x = "A"
>>> y = "B"
>>> assert(eval('\{"{}": "{}"\}'.format(x, y)) == str({x: y}))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: '"{}"
Saqib Ali
  • 11,931
  • 41
  • 133
  • 272

1 Answers1

1

You can escape curly braces by adding double curly braces i.e {{ and }}.

To generate the string:

>>> x = 'A'
>>> y = 'B'
>>> dict_str = "{{'{}': '{}'}}".format(x,y)
>>> dict_str
"{'A': 'B'}"
Vishnu Dasu
  • 533
  • 5
  • 18