[英]Python string: how to query a dictionary inside a list, which are inside a dictionary
目标:从下面的字符串中,我需要并排提取API返回的“键”值和“查询”值。
我不是Python专家,但在我看来,我要打的API会在列表内返回一个字典,而列表本身也在字典内。
这似乎是问题的症结所在[清单的参与]。 请注意,API可能会返回多行,例如以下一行。
{'Condition1': 'True', 'Load': 'Normal', 'query': 'xyz', 'results': [{'F1': 'abc', 'F2': 'def','Key': 'dfg4325'}]}
从上面的示例中,我试图检索一个组合字符串,即类似于CSV的如下所示:
'xyz','dfg4325'
我尝试了许多策略,但没有任何效果。 列表字典中的“键”字段始终为字母数字-否则,我会为此感到困惑。
任何想法将不胜感激。 我用谷歌搜索,只是找不到正确的答案。
您可以迭代字典和列表以查找“ key”的值,例如,
for key, val in response.items():
if isinstance(val, list):
for dic in val:
if 'Key' in dic:
val_of_key = dic.get('Key')
break
if isinstance(search_response["results"], list):
for dic in search_response["results"]:
if "Key" in dic:
val_of_key = dic["Key"]
decoded_Key = (val_of_key + "|" + search_response["query"]+ "\n")
# setup a dummy text file in the same fldr as the pycharm project
# appends the results to a text
with open("dummy.txt", "a") as query_file:
query_file.write(decoded_Key)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.