KeyError in .format() python 2.6 KeyError in .format() python 2.6 json json

KeyError in .format() python 2.6


It's a doomed idea to try to apply str.format in json dumps, for several reasons, the main one being that the enclosing {} of the string dump conflicts/loses the formatting.

I'd suggest to pre-process your dictionary beforehand with named fields:

import jsondata = {        "u_in_record_type": '{type}',        "u_company_source": '{source}'    }type="Test"source="Source"new_data = {k:v.format(type=type,source=source) for k,v in data.items()}

Pre-python 2.7 syntax (dict comprehensions not available yet):

new_data = dict((k,v.format(type=type,source=source)) for k,v in data.items())

the dictionary comprehension applies the arguments to all the records, which pick the ones that they need. Then you can dump that version of the dictionary.

A dict-based variant (which can be handy when there are a lot of variables) would be:

fd = dict(type="Test",source="Source")new_data = {k:v.format(**fd) for k,v in data.items()}