如何从字典中的字典获取数据避免在 python 中使用 for 循环

How to obtain data from a dict inside a dict avoiding to use a for loop in python

数据示例:

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的"data": vector[0:299]的值

我已经尝试了

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

但是我得到了错误

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

获取我使用的 'hit' 字典中的索引

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 向量。

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

你可以使用Python 理解列表(虽然这可以被认为是一个循环):

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

如果您不需要遍历整个数据结构,您可以使用 Python generators(懒惰的):

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 字典(散列映射)快得多。