2015-07-28 73 views
0

我有Python中的列表如下:轉換列表以字典使用python

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 = { 
    'TimeStampUTC' : [20150716143000, 20150716143000, 20150716143000, 20150716143000, 20150716143000], 
    'Turbine': ['RENDG-01', 'RENDG-02', 'RENDG-03', 'RENDG-04', 'RENDG-05'], 
    'Power': [81, 82, 83, 84, 85] 
} 

怎麼能這樣做?

回答

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

太謝謝你了扎克。該片段是工作精細。 –

+0

嘿,我們可以從u'RENDG-03'中刪除字符'u',並將其字典值推送爲'RENDG-03'。 –

+0

字符'u'表示它是一個unicode對象。你可以使用'x.encode(charset)'(例如'x.encode('utf8')')將它編碼爲你需要的任何字符集。 – Zac

0

不使用拉鍊(這是看中了),您可以創建使用

# 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:]] 
+0

謝謝redimp。 Zac提出的片段是在Tuple中使用密鑰,但是您的片段將我帶入了我正在查看的值列表中。這正是我所期待的。 –

+0

嗨,我們可以從u'RENDG-03'中刪除字符'u',並將其字典值推送爲'RENDG-03'。 –

+0

'u'是unicode字符串的指示符。要正確處理unicode字符串,請參閱https://docs.python.org/2/howto/unicode.html。既然你獲得了整數並浮在你的列表中,那麼最好不要投。對於這個例子,使用:d ['Turbine'] = [str(x)for d ['Turbine']] – redimp

0

列表中你可以這樣做:

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