Search code examples
pythonjsonpython-2.7string-formatting

KeyError in .format() python 2.6


I try to string format {0} and {1} with the variables type and source but I get KeyError:

import json
data = {
        "u_in_record_type": '{0}',
        "u_company_source": '{1}'
    }
data = json.dumps(data)
type="Test"
source="Test"
print(data.format(type, source))
Traceback (most recent call last):
  File "untitled.py", line 10, in <module>
    print(data.format(type, source))
KeyError: '"u_in_record_type"'

Solution

  • 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 json
    
    data = {
            "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()}