-1

The goal: from the string below I need to extract, side by side, the 'key' value and the 'query' value, which are returned by an API.

I'm not a Python expert, but to me it seems that the API that I'm hitting returns a dictionary inside a list, which themselves are inside a dictionary.

That seems to be the crux of the issue [the involvement of the list]. Note, the API may return multiple lines such as the one below.

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

from the example above, I'm trying to retrieve a combined string that would be i.e. like a CSV as follows:

'xyz','dfg4325'

I've tried a number of tactics but nothing is working. The 'key' field inside the list's dictionary is always alpha-numeric - otherwise I'd have a hack for it.

Any thoughts would be appreciated. I googled this and just can't hit the right answer.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
marucho21
  • 23
  • 1
  • 5
  • 5
    Accessing lists and dictionaries is a basic task, covered in any Python tutorial. What "tactics" have you tried? – TigerhawkT3 Mar 06 '17 at 23:42

2 Answers2

1

You can iterate a dict and a list to find the value of 'key', for example,

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
Hou Lu
  • 3,012
  • 2
  • 16
  • 23
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)
marucho21
  • 23
  • 1
  • 5