Note that there are some explanatory texts on larger screens.

plurals
  1. POConvert a list into a nested dictionary
    text
    copied!<p>For example I have</p> <pre><code>x = ['a','b','c'] </code></pre> <p>I need to convert it to:</p> <pre><code>y['a']['b']['c'] = '' </code></pre> <p>Is that possible?</p> <p>For the background, I have a config file which contains dotted notation that points to a place in some json data. I'd like to use the dotted notation string to access that specific data in the json file. For example, in the config:</p> <pre><code>path_to_data = "user.name.first_name" </code></pre> <p>I'd like my script to recognize that as:</p> <pre><code>json_data["user"]["name"]["first_name"] </code></pre> <p>so I can get the value of the first_name field. I converted the original string into a list, and now I don't know how to convert it to a nested dict.</p> <p><strong>EDIT</strong>: There is an existing data structure that I need to apply the dict with. Let's say:</p> <pre><code>m = {'a': {'b': {'c': 'lolcat'}}} </code></pre> <p>so that</p> <pre><code>m['a']['b']['c'] </code></pre> <p>gives me 'lolcat'. If I get the right dictionary structure (as some of the replies did), I would still need to apply this to the existing dictionary 'm'. </p> <p>So, again, I get this from a config file:</p> <pre><code>c = 'a.b.c' </code></pre> <p>That I converted to a list, thinking this will make things easier:</p> <pre><code>x = ['a','b','c'] </code></pre> <p>Now I have a json-like data structure:</p> <pre><code>m = {'a': {'b': {'c': 'lolcat'}}} </code></pre> <p>So the nested dict generated from 'x' should be able to traverse 'm' so that</p> <pre><code>m['a']['b']['c'] </code></pre> <p>gets me the cat.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload