Search code examples
pythondictionarynested

pythonic way to manipulate nested dict from dotted path?


I have a nested dictionary, an encryption function and a dotted path, I want to apply my encryption function to encrypt specific field. Example:

mydict

{"a":{
     ...
     "b":{
          ...
          "c":"value"
           }
      }
 }

field path: a.b.c

I want to execute encryption function on c value and modify my dict. What's the most efficent and pythonic way?


Solution

  • I'm guessing what you mean is have the number of nestings be variable according to a string like 'a.b.c':

    d = {"a":{"b":{"c":"value"}}}
    dotted = 'a.b.c'
    
    paths, current = dotted.split('.'), d
    for p in paths[:-1]:
        current = current[p]
    current[paths[-1]] = encrypt(current[paths[-1]])
    

    this will modify the given dictionary d to be

    {"a":{"b":{"c":"whatever the encrypted value is"}}}