使用python将List转换为Dictionary

时间:2015-07-28 10:44:33

标签: list python-2.7 parsing dictionary

我在python中有一个List,如下所示:

lst = [
    [u'TimeStampUTC', u'Turbine', u'Power'], 
    [20150716143000.0, u'RENDG-01', 81], 
    [20150716143000.0, u'RENDG-02', 82], 
    [20150716143000.0, u'RENDG-03', 83], 
    [20150716143000.0, u'RENDG-04', 84], 
    [20150716143000.0, u'RENDG-05', 85]
]

我需要将它转换为Dictionary,如下所示:

dictionary = {
    'TimeStampUTC' : [20150716143000, 20150716143000, 20150716143000, 20150716143000, 20150716143000], 
    'Turbine': ['RENDG-01', 'RENDG-02', 'RENDG-03', 'RENDG-04', 'RENDG-05'], 
    'Power': [81, 82, 83, 84, 85]
}

怎么可以这样做?

3 个答案:

答案 0 :(得分:0)

dictionary = dict(zip(lst[0], zip(*lst[1:])))

答案 1 :(得分:0)

不使用zip(非常棒),您可以使用

创建列表
# create empty dictionary
d = {}
# iterate through the keys in the first entry of the list
for c,key in enumerate(lst[0]):
    # add to the dictionary using the key from the
    # first row and the c-th column of every other row
    d[str(key)] = [x[c] for x in lst[1:]]

答案 2 :(得分:0)

你可以这样做:

my_dict={}
for ind,key in enumerate(lst[0]):
    my_dict[key]=[lst[i][ind] for i in range(1,len(lst))]