MathiasH MathiasH - 1 year ago 67
Python Question

add multiple values per key to a dictionary depending on if statement

I need to transform a path into a python dictionary where

parent folder = key
folder content = values (e.g 'a/foo' 'a/bar' 'b/root' 'b/data'
needs to be
{ 'a': ['foo', 'bar'], 'b': ['root', 'data']}
) I got my dictionary initialized
d = {'a': [], 'b': [] }
and my list of values
l = ['a/foo', 'a/bar', 'b/root', 'b/data']

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')

for key in d:
myIndex = len(key)
for value in l:
if value[:myIndex] == key:

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

Answer Source

Considering the structure of your result, collections.defaultdict can handle this more easily:

from collections import defaultdict

d = defaultdict(list)

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

for path in lst:
   k, v = path.split('/')

# defaultdict(<class 'list'>, {'b': ['root', 'data'], 'a': ['foo', 'bar']})