【问题标题】:Initialize List to a variable in a Dictionary inside a loop将列表初始化为循环内字典中的变量
【发布时间】:2014-05-12 02:27:56
【问题描述】:

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

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

谢谢。

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    列表和字典推导可以在这里提供帮助...

    给定

    In [72]: root_values
    Out[72]:
    [{'name': 'red', 'value': 2},
     {'name': 'red', 'value': 3},
     {'name': 'red', 'value': 2},
     {'name': 'green', 'value': 7},
     {'name': 'green', 'value': 8},
     {'name': 'green', 'value': 9},
     {'name': 'blue', 'value': 4},
     {'name': 'blue', 'value': 4},
     {'name': 'blue', 'value': 4}]
    

    如下所示的item() 之类的函数可以提取具有特定名称的值:

    In [75]: def item(x): return [m['value'] for m in root_values if m['name']==x]
    In [76]: item('red')
    Out[76]: [2, 3, 2]
    

    那么,这只是字典理解的问题......

    In [77]: {x:item(x) for x in ['red', 'green', 'blue']  }
    Out[77]: {'blue': [4, 4, 4], 'green': [7, 8, 9], 'red': [2, 3, 2]}
    

    【讨论】:

      【解决方案2】:

      您的代码没有将元素附加到列表中;相反,您正在用单个元素替换列表。要访问现有字典中的值,您必须使用索引,而不是属性查找(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'])
      

      defaultdictdict 子类,如果映射中尚不存在键,则使用 __missing__ hook on dict 自动实现值。

      或使用dict.setdefault():

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

      【讨论】:

        猜你喜欢
        • 2011-05-24
        • 1970-01-01
        • 2014-04-07
        • 2012-06-13
        • 2012-01-02
        • 2021-12-08
        • 2021-12-22
        • 1970-01-01
        • 2011-04-02
        相关资源
        最近更新 更多