add multiple values per key to a dictionary depending on if statement
<p>I need to transform a path into a python dictionary where <code>parent folder = key</code> and <code>folder content = values (e.g 'a/foo' 'a/bar' 'b/root' 'b/data'</code> needs to be <code>{ 'a': ['foo', 'bar'], 'b': ['root', 'data']}</code>) I got my dictionary initialized <code>d = {'a': [], 'b': [] }</code>and my list of values <code>l = ['a/foo', 'a/bar', 'b/root', 'b/data']</code></p>

<p>I did a nested for loop with an if statement who takes care of saying which value should be assigned to with key and remove the said key from the value path (e.g 'a/root' becomes 'root')</p>

<pre><code>for key in d:
    myIndex = len(key)
    for value in l:
        if value[:myIndex] == key:
            d[key].append(value[myIndex+1:])
</code></pre>

<p>The thing is that I get the values in the right format exept that I get all of them for each key <code>{ a: ['foo', 'bar', 'root', 'data'], b: ['foo', 'bar', 'root', 'data'] }</code> as if my if statement is simply being ignored. If someone has an idea of the problem! Thanks</p>

<p>Considering the structure of your result, <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>collections.defaultdict</code></a> can handle this more easily:</p>

<pre><code>from collections import defaultdict

d = defaultdict(list)

lst = ['a/foo', 'a/bar', 'b/root', 'b/data']

for path in lst:
   k, v = path.split('/')
   d[k].append(v)

print(d)
# defaultdict(&lt;class 'list'&gt;, {'b': ['root', 'data'], 'a': ['foo', 'bar']})
</code></pre>

python dictionary