2017-08-28 264 views
-7

我想列出列表並將其轉換爲字典。見下面python字典 - 列表字典

yearend = [['empl','rating1','rating2','rating3'],['mike','4','4','5'], 
['sam','3','2','5'],['doug','5','5','5']]  
extract the employee names 
employee = [item[0] for item in yearend] #select 1st item from each list 
employee.pop(0) # pop out the empl 
print(employee) 
### output################################################## 
##['mike', 'sam', 'doug']################################### 
###Output################################################### 
###extract the various rating types 
yearend1 = yearend [:] # make a copy 
rating = yearend1.pop(0) # Pop out the 1st list 
rating.pop(0) 
print(rating) 
### output################################################## 
##['rating1', 'rating2', 'rating3']######################### 
###Output################################################### 
# pick employee and rating and convert rating to numeric 
empl_rating = {t[0]:t[1:] for t in yearend1} 
for key,value in empl_rating.items(): 
value = list(map(int, value)) 
empl_rating[key] = value 
print(empl_rating) 
### output################################################## 
##{'mike': [4, 4, 5], 'sam': [3, 2, 5], 'doug': [5, 5, 5]}## 
###Output################################################### 

代碼我提取像上面現在蔭試圖建立到字典(New_dicts)的數據,這樣,當

New_dicts['sam']['rating1'] 

我得到3或

New_dicts['doug']['rating3'] 

我得到了5.我正在努力的是如何將這些數據放在一起?

+2

這不是一個代碼編寫的服務。請參閱[問] –

回答

0
def todict(ratings) : 
    a ={} 
    a["rating1"] = ratings [0] 
    a["rating2"] = ratings [1] 
    a["rating3"] = ratings [2] 
    return a 

一個爲您解決問題的辦法是獲得與標題擺脫了第一排的,然後就去做: {item[0] : todict(item[1:]) for item in your_list}

BTW這種溶膠是基於關閉的,你想怎麼建立索引。我確信那裏有更通用的解決方案。

因爲你想要什麼本質上只是一個嵌套的字典

0

您可以使用dict comprehension

New_dicts = {line[0]: {yearend[0][i + 1]: int(rating) for i, rating in enumerate(line[1:])} for line in yearend[1:]}