将List初始化为循环内的Dictionary中的变量

Fmr*_*bio 10 python dictionary

我已经在Python工作了一段时间,我使用"try"和"except"解决了这个问题,但我想知道是否有另一种方法来解决它.

基本上我想创建一个这样的字典:

example_dictionary = {"red":[2,3,4],"blue":[6,7,8],"orange":[10,11,12]}
Run Code Online (Sandbox Code Playgroud)

所以,如果我有一个包含以下内容的变量:

root_values = [{"name":"red","value":2},{"name":"red","value":3},{"name":"red","value":4},{"blue":6}...]
Run Code Online (Sandbox Code Playgroud)

我实现example_dictionary的方法是:

example_dictionary = {}
for item in root_values:
   try:
       example_dictionary[item.name].append(item.value)
   except:
       example_dictionary[item.name] =[item.value]
Run Code Online (Sandbox Code Playgroud)

我希望我的问题很清楚,有人可以帮我解决这个问题.

谢谢.

Mar*_*ers 24

您的代码不会将元素附加到列表中; 而是用单个元素替换列表.要访问现有词典中的值,必须使用索引,而不是属性查找(item['name']不是item.name).

用途collections.defaultdict():

from collections import defaultdict

example_dictionary = defaultdict(list)
for item in root_values:
    example_dictionary[item['name']].append(item['value'])
Run Code Online (Sandbox Code Playgroud)

defaultdict是一个dict子类,如果映射中尚不存在键,则使用__missing__hookdict来自动实现值.

或使用dict.setdefault():

example_dictionary = {}
for item in root_values:
    example_dictionary.setdefault(item['name'], []).append(item['value'])
Run Code Online (Sandbox Code Playgroud)