在读取文件时创建Python字典

时间:2014-05-02 03:44:37

标签: python dictionary coding-style

我有一个从带有标题

的文本文件(文件名)派生的列表
mylist = [l.split() for l in open(filename, "r")]

mylist = [['A','B','C','D'],['1','2','3','4'],['10','20','30','40'],['100','200','300','400']]

我希望创建一个直接读取文件的字典,以便将代码行保存为:

mtlist_dist = {A: ['1','10','100'], B: [''2,'20','200'], C: ['3','30','300'], D: ['4','40','400']}

2 个答案:

答案 0 :(得分:3)

您可以使用zipdictionary comprehension

轻松完成此操作
>>> mylist = [['A','B','C','D'],['1','2','3','4'],['10','20','30','40'],['100','200','300','400']]
>>> {x[0]:x[1:] for x in zip(*mylist)}
{'A': ('1', '10', '100'), 'C': ('3', '30', '300'), 'B': ('2', '20', '200'), 'D': ('4', '40', '400')}
>>> {x[0]:list(x[1:]) for x in zip(*mylist)}
{'A': ['1', '10', '100'], 'C': ['3', '30', '300'], 'B': ['2', '20', '200'], 'D': ['4', '40', '400']}
>>>

在Python 3.x中,使用extended iterable unpacking

,解决方案变得更加简洁
>>> mylist = [['A','B','C','D'],['1','2','3','4'],['10','20','30','40'],['100','200','300','400']]
>>> {x:y for x,*y in zip(*mylist)}
{'D': ['4', '40', '400'], 'A': ['1', '10', '100'], 'C': ['3', '30', '300'], 'B': ['2', '20', '200']}
>>>

答案 1 :(得分:1)

你可以这样做:

my_dict = dict(zip(mylist[0], zip(*mylist[1:])))

>>> print my_dict
{'A': ('1', '10', '100'), 'C': ('3', '30', '300'), 'B': ('2', '20', '200'), 'D': ('4', '40', '400')