初始化List到循环内的Dictionary中的变量 [英] Initialize List to a variable in a Dictionary inside a loop

查看:113
本文介绍了初始化List到循环内的Dictionary中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

  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 on dict 以自动实现值,如果该关键字在映射中还不存在。



或使用 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'], 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 subclass that uses the __missing__ hook on dict 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆