0

I was trying to generate a dynamic id which comes from a an object at runtime and insert this into database.

'{"mykey": {value}}'.format(value=obj.id)

but this gives an error

KeyError: '"mykey"'

expected result:

'{"mykey": 4}' # assuming obj.id = 4

I know I can use json.dumps but I do not wish to use json for such a simple task and had to resort to:'{"mykey": %s}' %(obj.id,)

But I am curious to know a way to do this with format.

dnit13
  • 2,478
  • 18
  • 35

1 Answers1

4

You need to escape the {:

>>> value = 4
>>> '{{"mykey": {value}}}'.format(value=value)
'{"mykey": 4}'

You can also access the object properties inside the format template passing in obj in a context:

>>> from collections import namedtuple
>>> Object = namedtuple('Object', 'id')
>>> obj = Object(id=4)
>>> obj.id
4
>>> '{{"mykey": {obj.id}}}'.format(obj=obj)
'{"mykey": 4}'

Same goes for the format strings coming up in Python 3.6:

>>> value = 4
>>> f'{{"mykey": {value}}}'
'{"mykey": 4}'
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195