Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 257
Giuseppe Avatar asked Jun 05 '26 21:06

Giuseppe


1 Answers

Maybe a little too late and tricky but to be functional:

from functools import reduce

d = {'a': {'b': {'c': 'value'}}}
path = 'a.b.c'

# result will be 'value'
result = reduce(dict.__getitem__, path.split('.'), d)
like image 122
Masked Man Avatar answered Jun 07 '26 12:06

Masked Man



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!