gpt4 book ai didi

python方法具有1个变量的嵌套字典

转载 作者:行者123 更新时间:2023-12-01 00:34:03 25 4
gpt4 key购买 nike

我发现很难命名这个问题,但它一定是一个简单的问题,而且我错过了一些基本的东西。

假设我有以下 Python dict() :

import json

dct = dict()
dct['hits'] = dict()
dct['hits']['hits'] = dict()
dct['hits']['hits']['a'] = 'b'
dct['hits']['hits']['b'] = 'c'
dct['aggregations'] = dict()
dct['aggregations']['a'] = 1
dct['aggregations']['b'] = 2

print(json.dumps(dct, indent=2))

{
"hits": {
"hits": {
"a": "b",
"b": "c"
}
},
"aggregations": {
"a": 1,
"b": 2
}
}

这可能看起来很熟悉,因为它是 ElasticSearch 返回结果的结构。

我正在构建一个使用该结果的函数。但有时我想访问dct['hits']['hits'],有时我想访问dct['aggregations']

当然,我会使用一个带有变量的函数来建议我想要访问哪个字段,如下所示:

def foo(field):
return dct[field]

如果 field='aggregations' 一切都很好。但是,当我希望字段为 ['hits']['hits'] 时,我该怎么办?

<小时/>

解决这个问题的一种方法(但它很丑陋),迭代方法:

def foo(fields=('hits','hits')):
wanted = dct
for field in fields:
wanted = wanted[field]
return wanted

a = foo()
a
Out[47]: {'a': 'b', 'b': 'c'}
a = foo(('aggregations',))
a
Out[51]: {'a': 1, 'b': 2}
<小时/>

我尝试修改的实际功能:

def execute_scroll_query(es_client, query, indexes):
try:
response = es_client.search(index=indexes, scroll='2m', size=1000, body=query)
scroll_size = len(response['hits']['hits'])
sid = response['_scroll_id']
while scroll_size > 0:
try:
for hit in response['hits']['hits']:
yield hit
response = es_client.scroll(scroll_id=sid, scroll='2m')
sid = response['_scroll_id']
scroll_size = len(response['hits']['hits'])
except Exception:
print("Unexpected Exception while scrolling")
except Exception:
print("Unexpected Exception while fetching")

最佳答案

您可以使用functools.reduce,但在幕后,它使用迭代,并且可能不如显式迭代高效:

from functools import reduce

def foo(d, keys):
return reduce(lambda x, y: x[y], keys, d)

foo(dct, ['hits', 'hits', 'a'])
#'b'

关于python方法具有1个变量的嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57941387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com