1

I have a list of path like ['aaa/aaa.csv', 'aaa/bbb.csv', 'aaa/ccc.csv']. How can it be converted to dictionary like {'aaa':['aaa.csv', 'bbb.csv', 'ccc.csv'] and so on with first folder in path is equal to others?

I tried this code, but got confused what to do next.

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
1
  • 1
    Just a word of warning: with the way you're currently using split, you may run into trouble if you encounter multiply nested directories, e.g. /aaa/bbb/ccc.csv Commented Aug 27, 2015 at 12:52

5 Answers 5

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']}
Sign up to request clarification or add additional context in comments.

1 Comment

Could clean up a bit with for key,val in [x.split("/") for x in lst]:
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:]))

Comments

0

You can try this:

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

Output:

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

Comments

0

You can also use a defaultdict for this:

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

This will also work for nested directories by putting the full path as the key.

Comments

-1
path_dict = {}

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

1 Comment

What happens when you have 2 files with the same path?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.