使用字典理解从嵌套列表创建字典

时间:2016-02-26 08:41:19

标签: python dictionary-comprehension

有没有办法用嵌套列表创建一个字典,但是对于特定的索引? 我输入了:

 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:[] }

有没有办法使用字典理解来指定它?

2 个答案:

答案 0 :(得分:1)

这样做:

>>> 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: []}

答案 1 :(得分:0)

由于您只想要前两列,您可以简单地循环它们。您可以使用嵌套列表推导从前两列创建一个展平列表,并使用dict.fromkeys通过指定公共值创建一个可迭代的字典,并使用collections.OrderedDict()来保持顺序:< / p>

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