我有一个变量输出,它可以取值#1,#2, 我正在努力获得"原因"如果它存在,正如您从#1中看到的那样它总是不存在,有人可以建议如何做到这一点吗?
output =
#1: {"took":42,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":0,"max_score":null,"hits":[]}}
#2: {"took":88,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":1,"max_score":1.0,"hits":[{"_index":"dispatcher","_type":"lookaheadDV","_id":"832238","_score":1.0, "_source" : {"reasons": ["12345 is associated with data in an invalid state"]}}]}}
输出: -
12345 is associated with data in an invalid state
答案 0 :(得分:0)
好吧,从逻辑开始:
hits
内的hits
可能始终存在...此外,hits
看起来是一个列表,因此您可以测试hits
(hits
内部})存在,如果它不是空的(例如,你可以测试它的长度)。
一旦你知道hits
在那里,就必须进入那个对象并检查你要找的值是否存在。
如果在Python中有字典,则可以使用以下语法检索值:
new_value = some_dictionary.get('some_key', None)
如果没有与该键相关联的值,那么最后的值“None”是Python给我的值。你可以在那里放置你想要的任何值,然后在以后检查:
new_value = some_dictionary.get('some_key', 'BETTER ASK STACKOVERFLOW')
你必须尝试一下。使用REPL。
此外,以下内容不是我在Python中见过的任何内容。是什么给了你这个错误信息:
12345 is associated with data in an invalid state
答案 1 :(得分:0)
这应该这样做:
adict = {"took":42,"timed_out":False,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":0,"max_score":"null","hits":[]}}
bdict = {"took":88,"timed_out":False,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":1,"max_score":1.0,"hits":[{"_index":"dispatcher","_type":"lookaheadDV","_id":"832238","_score":1.0, "_source" : {"reasons": ["12345 is associated with data in an invalid state"]}}]}}
def get_reasons(some_dict):
output = ""
try:
output = some_dict.get("hits").get("hits")[0].get("_source").get("reasons")
except:
pass
return output
print get_reasons(adict)
print get_reasons(bdict)
不会为第一个字典打印任何内容并打印
12345 is associated with data in an invalid state
为第二本词典。
PS:我在您的词典中将false
更改为False
并将null
更改为"null"
。
答案 2 :(得分:0)
在必要时忽略KeyError
。可能有多种原因,因此以下代码将它们全部收集到列表中,然后使用', '
作为分隔符连接在一起。
value = { "took":88,"timed_out":False,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":1,"max_score":1.0,"hits":[{"_index":"dispatcher","_type":"lookaheadDV","_id":"832238","_score":1.0, "_source" : {"reasons": ["12345 is associated with data in an invalid state"]}}]}}
reasons = []
for i in value['hits']['hits']:
try:
reasons.extend(i['_source']['reasons'])
except KeyError:
pass
reason = ', '.join(reasons)