【问题标题】:Create a list of an inner value from a dict of dicts从字典的字典创建一个内部值列表
【发布时间】:2016-03-28 16:37:49
【问题描述】:

我正在尝试找出 dicts 字典的内部值的最大值和最小值。

dict 看起来像这样:

{'ALLEN PHILLIP K': {'bonus': 4175000,
                     'exercised_stock_options': 1729541,
                     'expenses': 13868},
 'BADUM JAMES P': {'bonus': 'NaN',
                   'exercised_stock_options': 257817,
                   'expenses': 3486},
 ...
}

我想找出所有字典中的最小和最大 exercised_stock_options

我尝试使用 pandas 来执行此操作,但无法找到适当调整数据的方法。然后,我在 Python 中尝试了一个简单的 for 循环。我的 for 循环代码不起作用,我不知道为什么(dicts 的字典称为data_dict):

stock_options=[]
for person in range(len(data_dict)):
    stock_options.append(data_dict[person]['exercised_stock_options'])
print stock_options

然后我要取列表的最大值和最小值。

知道为什么这段代码不起作用吗?有什么替代方法可以计算字典的内部值的最大值和最小值吗?

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    这是一种方法,它使用列表推导从每个字典中获取 exercised_stock_options,然后从数据中打印出最小值和最大值。忽略示例数据,您可以根据需要对其进行修改。

    d = {'John Smith':{'exercised_stock_options':99},
         'Roger Park':{'exercised_stock_options':50},
         'Tim Rogers':{'exercised_stock_options':10}}
    data = [d[person]['exercised_stock_options'] for person in d]
    print min(data), max(data)
    

    【讨论】:

      【解决方案2】:

      您正在使用范围来获取主词典的索引号。你真正应该做的是获取字典的键而不是索引。也就是说,人是每个人的名字。因此,当person == 'ALLEN PHILLIP K' datadict[person] 现在获取该键的字典时。

      注意Use items() to iterate across dictionary 表示最好使用d, v = data_dict.items() 而不是循环遍历字典本身。还要注意 Python 2 和 Python 3 之间的区别。

      people=[]
      stock_options=[]
      for person, stock_data in data_dict.items():
          people.append(person)
          stock_options.append(stock_data['exercised_stock_options'])
          # This lets you keep track of the people as well for future use
      print stock_options
      mymin = min(stock_options)
      mymax = max(stock_options)
      # process min and max values.
      

      最佳实践

      使用 items() 遍历字典

      下面的更新代码演示了迭代的 Pythonic 风格 通过字典。当您在 for 循环中定义两个变量时 结合对字典上的 items() 的调用,Python 自动将第一个变量分配为其中的键名 字典,第二个变量作为对应的值 那把钥匙。

      d = {"first_name": "Alfred", "last_name":"Hitchcock"}
      
      for key,val in d.items():
          print("{} = {}".format(key, val))
      

      Python 2 和 Python 3 的区别

      在 python 2.x 中,上面使用 items 的示例将返回一个列表 包含复制的字典键值对的元组。在 为了不复制并加载整个字典的键和 列表中的值到内存中,您应该更喜欢迭代项 方法简单地返回一个迭代器而不是一个列表。在 Python 中 3.x iteritems 被移除,items 方法返回视图对象。与元组相比,这些视图对象的好处 包含副本是对字典所做的每一次更改都是 反映在视图对象中。

      【讨论】:

        【解决方案3】:

        您需要迭代您的字典.values() 并返回“exercised_stock_options”的值。您可以使用简单的列表推导来检索这些值

        >>> values = [value['exercised_stock_options'] for value in d.values()]
        >>> values
        [257817, 1729541]
        >>> min(values)
        257817
        >>> max(values)
        1729541
        

        【讨论】:

          【解决方案4】:

          几周前我发布了lifter 专门用于此类任务,我认为您可能会发现它很有用。 这里唯一的问题是你有一个映射(一个字典的字典)而不是一个常规的迭代。

          这是一个使用升降机的答案:

          from lifter.models import Model
          
          # We create a model representing our data
          Person = Model('Person')
          
          # We convert your data to a regular iterable
          iterable = []
          for name, data in your_data.items():
              data['name'] = name
              iterable.append(data)
          
          # we load this into lifter
          manager = Person.load(iterable)
          
          # We query the data
          results = manager.aggregate(
              (Person.exercised_stock_options, min),
              (Person.exercised_stock_options, max),
          )
          

          您当然可以使用列表推导获得相同的结果,但是,有时使用专用库会很方便,特别是如果您想在获取结果之前使用复杂查询过滤数据。例如,您可以只为费用少于 10000 的人获取最小值和最大值:

          # We filter the data
          queryset = manager.filter(Person.expenses < 10000)
          
          # we apply our aggregate on the filtered queryset
          results = queryset.aggregate(
              (Person.exercised_stock_options, min),
              (Person.exercised_stock_options, max),
          )
          

          【讨论】:

            猜你喜欢
            • 2020-08-31
            • 1970-01-01
            • 1970-01-01
            • 2018-09-18
            • 1970-01-01
            • 1970-01-01
            • 2017-05-05
            • 1970-01-01
            • 2018-11-06
            相关资源
            最近更新 更多