首页 > 解决方案 > 如何从字典中的字典获取数据,避免在python中使用for循环

问题描述

数据示例:

response = {
  "took" : value1,
  "_shards" : {
    "total" : 2,
  },
  "hits" : {
    "total" : {
      "value" : 150,
    },
    "hits" : [
      {
        "_index" : "index1",
        "_type" : "_doc",
        "_source" : {
          "date" : "date1",
          "hit" : 1,
          "routing-key" : "id_key1",
          "data": vector1[0:299] 
        },
      },
      {
        "_index" : "index2",
        "_type" : "_doc",
        "_source" : {
          "date" : "date2",
          "hit" : 2,
          "routing-key" : "id_key2",
          "data": vector2[0:299] 
        },
      },
      {
        "_index" : "index3",
        "_type" : "_doc",
        "_source" : {
          "date" : "date3",
          "hit" : 3,
          "routing-key" : "id_key3",
          "data": vector3[0:299] 
        },
      },
#...
# I am not going to copy the whole request but there are until 150 hits
#...
    ]
  }
}
   

现在我想从请求中的所有命中中获取位置 120 中的“数据”的值:vector[0:299]

我已经尝试做

vect_sol = response['hits']['hits'][:]['_source']['data'][120]

但我得到了错误

TypeError: list indices must be integers or slices, not str

要获取我使用过的“命中”字典中的索引

vect_sol = response['hits']['hits'][:]

它有效。for那么我如何通过循环在数据向量中获得所需的值

for i in range(hits):
   data_sol[i] = response['hits']['hits'][i]['_source']['data'][120]

这工作正常,但是当数据请求由 10,000 次或更多(可能更大)组成时,脚本需要时间来填充data_sol向量。

我猜是否有某种功能或不同的方式可以将数据作为请求获取,但会缩短脚本的执行时间。

标签: performancedictionaryfor-looppython-3.9

解决方案


您可以使用 Python理解列表(尽管这可以被视为一个循环):

vect_sol = [item['_source']['data'][120] for item in response['hits']['hits']]

如果您不需要遍历完整的数据结构,您可以使用 Python生成器(惰性):

vect_sol = (item['_source']['data'][120] for item in response['hits']['hits'])

或者,您可以使用更面向功能的代码(可能更快)map

vect_sol = map(lambda item: item['_source']['data'][120], response['hits']['hits'])

如果您想要更快的代码,我认为您应该将数据结构转换为相互关联的对象(定义明确的类)。这应该比使用带有字符串键(需要散列)的 Python 字典(散列映射)快得多。


推荐阅读