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']}}
不要使用'list'和'dict'作爲變量名;你掩蓋了內置的類型。來自輸入的'facultyA'數據發生了什麼? –
非常感謝Martijin!我嘗試類似res = defaultdict(list)時會遇到錯誤,但從未明白原因。我會記住它,絕對不會在將來使用list和dict作爲變量名稱。我錯誤地爲教師X選了一個教師隊伍;應該只有facultyX和facultyY。 – back4good