Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert this list into dictionary in Python?

I have a list like this:

paths = [['test_data', 'new_directory', 'ok.txt'], ['test_data', 'reads_1.fq'], ['test_data', 'test_ref.fa']]

I want to convert this into dictionary like this:

{'test_data': ['ok.txt', 'reads_1.fq'], 'test_data/new_directory', ['ok.txt']}

The list is dynamic. The purpose of this is to create a simple tree structure. I want to do this using itertools like this:

from itertools import izip
i = iter(a)
b = dict(izip(i, i))

Is something like this possible? Thanks

like image 300
pynovice Avatar asked Jun 17 '13 10:06

pynovice


2 Answers

can try this also,

list1=['a','b','c','d']
list2=[1,2,3,4]

we want to zip these two lists and create a dictionary dict_list

dict_list = zip(list1, list2)
dict(dict_list)

this will give:

dict_list = {'a':1, 'b':2, 'c':3, 'd':4 }
like image 126
SriSree Avatar answered Oct 28 '22 15:10

SriSree


Yes it is possible, use collections.defaultdict:

>>> from collections import defaultdict
>>> dic = defaultdict(list)
>>> lis = [['test_data', 'new_directory', 'ok.txt'], ['test_data', 'reads_1.fq'], 
for item in lis:                                                                                           
    key = "/".join(item[:-1])
    dic[key].append(item[-1])
...     
>>> dic
defaultdict(<type 'list'>,
{'test_data': ['reads_1.fq', 'test_ref.fa'],
 'test_data/new_directory': ['ok.txt']})

using simple dict:

>>> dic = {}
>>> for item in lis:
    key = "/".join(item[:-1])
    dic.setdefault(key, []).append(item[-1])
...     
>>> dic
{'test_data': ['reads_1.fq', 'test_ref.fa'],
 'test_data/new_directory': ['ok.txt']}
like image 44
Ashwini Chaudhary Avatar answered Oct 28 '22 15:10

Ashwini Chaudhary