根据if语句将每个键的多个值添加到字典中

时间:2016-09-20 12:56:15

标签: python dictionary

我需要将路径转换为python字典,其中parent folder = keyfolder content = values (e.g 'a/foo' 'a/bar' 'b/root' 'b/data'需要{ 'a': ['foo', 'bar'], 'b': ['root', 'data']})我的字典已初始化d = {'a': [], 'b': [] }和我的值列表{ {1}}

我做了一个带有if语句的嵌套for循环,它负责说明应该用key分配哪个值,并从值路径中删除所述键(例如' a / root'变为' 39;根&#39)

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

问题是我得到了正确格式的值,我得到了每个键for key in d: myIndex = len(key) for value in l: if value[:myIndex] == key: d[key].append(value[myIndex+1:]) 的所有值,好像我的if语句被忽略了。如果有人知道这个问题!感谢

3 个答案:

答案 0 :(得分:1)

考虑到结果的结构,collections.defaultdict可以更轻松地处理这个问题:

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(<class 'list'>, {'b': ['root', 'data'], 'a': ['foo', 'bar']})

答案 1 :(得分:0)

使用split拆分为文件夹和子文件夹。

d = {'a': [], 'b': [] }
l = ['a/foo', 'a/bar', 'b/root', 'b/data']
for key in d:
    for value in l:
        sep = value.split('/')
        if key == sep[0]:
            d[key].append(sep[1])
print(d)
# {'b': ['root', 'data'], 'a': ['foo', 'bar']}

答案 2 :(得分:0)

您的字典初始化方式有问题 customersDatabases

而不是:

customersDatabases = d # problem with keys initialization (pointer to same empty list)

尝试:

customersDatabases = dict(d) # new instance properly initialized
相关问题