从python列表中创建字典

时间:2015-08-27 12:48:24

标签: python list dictionary

我有一个像['aaa/aaa.csv', 'aaa/bbb.csv', 'aaa/ccc.csv']这样的路径列表。 如何将它转换为{'aaa':['aaa.csv', 'bbb.csv', 'ccc.csv']之类的字典,依此类推,路径中的第一个文件夹与其他文件夹相同?

我尝试了这段代码,但对下一步做什么很困惑。

list_split = [i.split('/') for i in list]

dic = {}
list_temp = []
for item in list_split:
    list_temp.append(item)
    if len(list_temp) < 2:
        pass
    else:
        for itemm in list_temp:
            pass

5 个答案:

答案 0 :(得分:3)

dic = {}
lst = ['aaa/aaa.csv', 'aaa/bbb.csv', 'aaa/ccc.csv']
for item in lst:
    slash = item.find('/')
    key = item[:slash]
    val = item[slash+1:]
    if dic.has_key(key):
        dic[key].append(val)
    else:
        dic[key] = [val]

>>> dic
{'aaa': ['aaa.csv', 'bbb.csv', 'ccc.csv']}

答案 1 :(得分:1)

original_list = ['aaa/aaa.csv', 'aaa/bbb.csv', 'aaa/ccc.csv', 'x/1.csv', 'y/2.csv']  # i added a couple more items to (hopefully) prove it works

dic = {}

for item in original_list:
    path = item.split('/')
    if path[0] not in dic:
        dic[path[0]] = []
    dic[path[0]].append('/'.join(path[1:]))

答案 2 :(得分:0)

你可以试试这个:

>>> L = ['aaa/aaa.csv', 'aaa/bbb.csv', 'aaa/ccc.csv']
>>> list_split = [tuple(i.split('/')) for i in L]
>>> newdict = {}
>>> for (key,item) in list_split:
    if key not in newdict:
        newdict[key]=[]
    newdict[key].append(item)

输出:

{'aaa': ['aaa.csv', 'bbb.csv', 'ccc.csv']}

答案 3 :(得分:0)

您也可以使用defaultdict

from collections import defaultdict

paths = ['aaa/aaa.csv', 'aaa/bbb.csv', 'aaa/ccc.csv', 'bbb/ccc.csv', 'aaa/bbb/ccc.csv']
dict = defaultdict(list)
for *key, value in [x.split('/') for x in paths]:
    dict['/'.join(key)].append(value)

print(dict.items())
print(dict['aaa'])

通过将完整路径作为键,这也适用于嵌套目录。

答案 4 :(得分:-1)

path_dict = {}

for path in path_list:
    if '/' in path:
        path_dict[path.split('/')[0]] = path.split('/')[1:]