Python字符串:如何查询列表中的字典,这些字典位于字典

时间:2017-03-06 23:41:00

标签: python list dictionary nested

目标:从下面的字符串中我需要并排提取由API返回的“key”值和“query”值。

我不是Python专家,但对我来说,似乎我正在点击的API会返回列表中的字典,这些字典本身就在字典中。

这似乎是问题的关键[列表的参与]。请注意,API可能会返回多行,例如下面的行。

{'Condition1': 'True', 'Load': 'Normal', 'query': 'xyz', 'results': [{'F1': 'abc', 'F2': 'def','Key': 'dfg4325'}]}

从上面的示例中,我正在尝试检索一个组合字符串,就像CSV一样,如下所示:

'xyz','dfg4325'

我尝试了很多策略,但没有任何效果。列表字典中的“key”字段始终是字母数字 - 否则我就会对它进行破解。

任何想法都将不胜感激。我用谷歌搜索了,但是无法找到正确的答案。

2 个答案:

答案 0 :(得分:1)

您可以迭代字典和列表以查找“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

答案 1 :(得分:1)

    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)
相关问题