【问题标题】:How to obtain data from a dict inside a dict avoiding to use a for loop in python如何从字典中的字典获取数据,避免在 python 中使用 for 循环
【发布时间】:2021-06-23 03:42:56
【问题描述】:

数据示例:

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

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

【问题讨论】:

    标签: performance dictionary for-loop python-3.9


    【解决方案1】:

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

    【讨论】:

    • 感谢 Jérôme,但正如您所说,这可以被视为一个循环。如果可能的话,我正在寻找的是替换某些功能的循环。再次感谢
    • 好的。我编辑了帖子以添加另一个版本。我不认为你可以在纯 Python 中做得更好。但是外部包可以为你做一些有趣的事情。更具体地说,您可以查看在 Python 中实现 LINKQ 的 Python 包(例如 this one)。
    • 非常感谢@Jérôme py_linq 库帮了很多忙。我避免了循环并且代码运行得更快:)
    猜你喜欢
    • 2020-05-16
    • 2022-11-17
    • 2021-07-08
    • 1970-01-01
    • 2018-12-01
    • 2017-04-05
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多