初始化List到循环内的Dictionary中的变量 [英] Initialize List to a variable in a Dictionary inside a loop
问题描述
基本上我想创建一个这样的字典:
example_dictionary = {red:[2,3,4],blue:[6,7,8],orange:[10,11,12]}
/ pre>
所以如果我有一个包含以下内容的变量:
root_values = [{name:red,value:2},{name:red,value:3},{name:red 4},{blue:6} ...]
我实现example_dictionary的方法是:
example_dictionary = {}
在root_values中的项目:
try:
example_dictionary [ item.name] .append(item.value)
除了:
example_dictionary [item.name] = [item.value]
我希望我的问题很清楚,有人可以帮助我。
谢谢。
解决方案您的代码不是将元素附加到列表中;而是用单个元素替换列表。要访问现有字典中的值,您必须使用索引,而不是属性查找(
item ['name']
,而不是item.name
)。
使用
collections.defaultdict()
:defaultdict
example_dictionary = defaultdict(list)
在root_values中的项目:
example_dictionary [item ['name']]。append(item ['value'])
defaultdict
是一个dict
子类,使用__缺少__
hook ondict
以自动实现值,如果该关键字在映射中还不存在。
或使用
dict.setdefault()
:示例_dictionary = {}
在root_values中的项目:
example_dictionary.setdefault(item ['name'],[])。append(item ['value'])
I have been working for a while in Python and I have solved this issue using "try" and "except", but I was wondering if there is another method to solve it.
Basically I want to create a dictionary like this:
example_dictionary = {"red":[2,3,4],"blue":[6,7,8],"orange":[10,11,12]}
So if I have a variable with the following content:
root_values = [{"name":"red","value":2},{"name":"red","value":3},{"name":"red","value":4},{"blue":6}...]
My way to implement the example_dictionary was:
example_dictionary = {} for item in root_values: try: example_dictionary[item.name].append(item.value) except: example_dictionary[item.name] =[item.value]
I hope my question is clear and someone can help me with this.
Thanks.
解决方案Your code is not appending elements to the lists; you are instead replacing the list with single elements. To access values in your existing dictionaries, you must use indexing, not attribute lookups (
item['name']
, notitem.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 adict
subclass that uses the__missing__
hook ondict
to auto-materialize values if the key doesn't yet exist in the mapping.or use
dict.setdefault()
:example_dictionary = {} for item in root_values: example_dictionary.setdefault(item['name'], []).append(item['value'])
这篇关于初始化List到循环内的Dictionary中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!