使用字典理解创建词典从嵌套列表
问题描述:
有没有办法创建一个嵌套列表,但对于特定索引的字典?
我输入:使用字典理解创建词典从嵌套列表
data = [[int, int, int], [int, int, int], [int, int,int]]
我想这样的线沿线的东西:
my_dictionary = {}
for x in data:
my_dictionary[x[0]] = []
my_dictionary[x[1]] = []
,但不必通过整个事情迭代。
例如:
data = [[a,b,c], [d,e,f], [g,h,i]]
# would leave me with:
my_dictionary = {a: [] , b:[], d:[], e:[], g:[], h:[] }
有没有指定这个使用字典解析的方法吗?
答
只是这样做:
>>> data
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> {d[i]:[] for i in (0,1) for d in data}
{1: [], 2: [], 4: [], 5: [], 7: [], 8: []}
答
既然你只是想前两列就可以简单地遍历他们。您可以使用嵌套列表理解,以创建前两列扁平化列表,并使用dict.fromkeys
创建字典通过指定共同的价值形成一个迭代,为了使用collections.OrderedDict()
保持顺序:
>>> from collections import OrderedDict
>>> my_dict = OrderedDict.fromkeys([i for sub in data for i in sub[:2]],[])
>>> my_dict
OrderedDict([('a', []), ('b', []), ('d', []), ('e', []), ('g', []), ('h', [])])
>>> my_dict['a']
[]
什么是你的*具体指数*以及您的预期产出是什么?你可以添加一个[最小,完整和可验证的例子](http://stackoverflow.com/help/mcve)到你的问题? – Kasramvd