2014-02-27 74 views
1

到字典中我想將列表轉換成一個字典如下:組元組的列表在Python

somelist = [("facultyX", "memberA", "Student"), 
      ("facultyX", "memberB", "Student"), 
      ("facultyX","memberC", "Programmer"), 
      ("facultyY", "memberD", "Student"), 
      ("facultyY", "memberE","PostDoc")] 

result = {'facultyX':{'Student':['memberA','memberB'], 
         'Programmer':['memberC']}, 
      'facultyY':{'Student':['memberD'], 
         'PostDoc':['memberE']}} 
+0

不要使用'list'和'dict'作爲變量名;你掩蓋了內置的類型。來自輸入的'facultyA'數據發生了什麼? –

+0

非常感謝Martijin!我嘗試類似res = defaultdict(list)時會遇到錯誤,但從未明白原因。我會記住它,絕對不會在將來使用list和dict作爲變量名稱。我錯誤地爲教師X選了一個教師隊伍;應該只有facultyX和facultyY。 – back4good

回答

5

隨着dict.setdefault()有點灑這並不難:

result = {} 

for fac, member, role in yourlist: 
    fac_data = result.setdefault(fac, {}) 
    fac_data.setdefault(role, []).append(member) 

演示:

>>> somelist = [("facultyX", "memberA", "Student"), 
...    ("facultyX", "memberB", "Student"), 
...    ("facultyX","memberC", "Programmer"), 
...    ("facultyY", "memberD", "Student"), 
...    ("facultyY", "memberE","PostDoc")] 
>>> result = {} 
>>> for fac, member, role in somelist: 
...  fac_data = result.setdefault(fac, {}) 
...  fac_data.setdefault(role, []).append(member) 
... 
>>> from pprint import pprint 
>>> pprint(result) 
{'facultyX': {'Programmer': ['memberC'], 'Student': ['memberA', 'memberB']}, 
'facultyY': {'PostDoc': ['memberE'], 'Student': ['memberD']}}