我已经在Python中工作了一段时间,并且已经使用“ try”和“ except”解决了这个问题,但是我想知道是否还有另一种方法可以解决它。
基本上我想创建一个像这样的字典:
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]
我希望我的问题很清楚,有人可以帮助我。
谢谢。
您的代码未将元素追加到列表;相反,您将列表替换为单个元素。要访问现有词典中的值,必须使用索引,而不是属性查找(item['name']
,不是item.name
)。
from collections import defaultdict
example_dictionary = defaultdict(list)
for item in root_values:
example_dictionary[item['name']].append(item['value'])
defaultdict
是一个dict
子类,如果键在映射中尚不存在,则使用__missing__
钩子dict
自动实现值。
example_dictionary = {}
for item in root_values:
example_dictionary.setdefault(item['name'], []).append(item['value'])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句