如何将此列表转换为 Python 中的字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17144889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert this list into dictionary in Python?
提问by pynovice
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:
该列表是动态的。这样做的目的是创建一个简单的树结构。我想使用这样的 itertools 来做到这一点:
from itertools import izip
i = iter(a)
b = dict(izip(i, i))
Is something like this possible? Thanks
这样的事情可能吗?谢谢
采纳答案by Ashwini Chaudhary
Yes it is possible, use collections.defaultdict:
是的,有可能,请使用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:
使用简单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']}
回答by SriSree
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
dict_list = zip(list1, list2)
dict(dict_list)
this will give:
这将给出:
dict_list = {'a':1, 'b':2, 'c':3, 'd':4 }

