Max Rukhlov
Max Rukhlov

Reputation: 331

make dictionary from list in python

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

Upvotes: 1

Views: 115

Answers (5)

Morgan Thrapp
Morgan Thrapp

Reputation: 9986

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.

Upvotes: 0

Sakib Ahammed
Sakib Ahammed

Reputation: 2480

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

Upvotes: 0

Jon Combe
Jon Combe

Reputation: 176

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

Upvotes: 1

hspandher
hspandher

Reputation: 16733

path_dict = {}

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

Upvotes: -1

Ananth
Ananth

Reputation: 4397

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

Upvotes: 3

Related Questions