我一直在Python工作了一段時間,我已經使用「嘗試」和「除了」解決了這個問題,但我想知道是否有另一種方法來解決它。初始化列表到一個循環內的字典中的變量
基本上我想創建這樣一個字典:
example_dictionary = {"red":[2,3,4],"blue":[6,7,8],"orange":[10,11,12]}
所以,如果我有以下內容的變量:
root_values = [{"name":"red","value":2},{"name":"red","value":3},{"name":"red","value":4},{"blue":6}...]
我的方式來實施example_dictionary是:
example_dictionary = {}
for item in root_values:
try:
example_dictionary[item.name].append(item.value)
except:
example_dictionary[item.name] =[item.value]
我希望我的問題很清楚,有人可以幫助我解決這個問題。
謝謝。