Recursively Modify Python Dictionary

If you need to modify the keys of a Python dictionary, a recursive function can be a useful way to work through the entire dictionary. This [gist](https://gist.github.com/schuettc/3875da7458e3573646599e70b7b17a61) is an example of how to do that.

Recursively Modify Python Dictionary

If you need to modify the keys of a Python dictionary, a recursive function can be a useful way to work through the entire dictionary. This gist is an example of how to do that.

def capitalize_keys(d):
    for k, v in d.copy().items():
        if isinstance(v, dict):
            d.pop(k)
            d[f"{k[0].upper() +k[1:]}"] = v
            capitalize_keys(v)
        else:
            d.pop(k)
            d[f"{k[0].upper() +k[1:]}"] = v
    return d

Each iteration through the function will look at the Value (v) and determine if it is a dict. If it is, the Key (k) will be removed and replaced with a capitalized version of the Key. Then, because we know the Value is a dict, the function will be called again with the Value as the input. If the Value is not a dict, we have reached the end of the dict and don't need to recurse again.

Other data manipulations can be made on the JSON object through these recursions as well.

For instance:

def capitalize_keys(d):
    for k, v in d.copy().items():
        if isinstance(v, dict):
            d.pop(k)
            d[f"{k[0].upper() +k[1:]}"] = v
            capitalize_keys(v)
        else:
            if k == "keyToChange":
                v = int(v)
            d.pop(k)
            d[f"{k[0].upper() +k[1:]}"] = v
    return d

In this example, the Value (v) of the Key (k) 'keyToChange' will be changed from a string to an int.

An example dictionary that has been processed:

[
  {
    appName: 'Capitalize',
    resources: {
      url: 'example.com',
      file: 'file.txt',
    },
  },
];

Result:

[
  {
    AppName: 'Capitalize',
    Resources: {
      Url: 'example.com',
      File: 'file.txt',
    },
  },
];