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

2023-12-12

我已经在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]

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

Thanks.


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

Use collections.defaultdict():

from collections import defaultdict

example_dictionary = defaultdict(list)
for item in root_values:
    example_dictionary[item['name']].append(item['value'])

defaultdict is a dict使用的子类__missing__勾搭上dict如果映射中尚不存在该键,则自动实现值。

or use dict.setdefault():

example_dictionary = {}
for item in root_values:
    example_dictionary.setdefault(item['name'], []).append(item['value'])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在循环内将 List 初始化为 Dictionary 中的变量 的相关文章

随机推荐