2017-08-28 185 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:]}