Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Break String into nested dictionary keys

Tags:

python

I have a string: candidate__name__first_name. I want to convert it into a nested dictionary of the form:

{ 
  candidate: {
    name: {
      first_name: 'MyName'
    }
  }
}

What would be the best way to do this?

like image 872
Apoorva Somani Avatar asked Sep 05 '26 09:09

Apoorva Somani


1 Answers

How about this:

recursive_key = 'candidate__name__first_name'
value = 'MyName'
for key in reversed(recursive_key.split('__')):
    value = {key: value}
print(value)
like image 106
Stephen Rauch Avatar answered Sep 07 '26 21:09

Stephen Rauch



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!