Carlissa Arrow
Carlissa Arrow

Reputation: 3

How to format python result to convert into a table?

I am using an API that pulls data about noise levels. When I run my code, I receive a resulting matrix of strings and integers. I want to put them in a table.

Last lines of code

r = requests.get(url, params=params, headers=headers)
json_data = r.json()
print(json_data['result'])

Result:

[{'airports': 0, 'traffictext': 'Active', 'localtext': 'Active', 'airportstext': 'Calm', 'score': 73, 'traffic': 25, 'scoretext': 'Active', 'local': 1}]

I want to convert this to read as a two-column table. I am also working in TouchDesigner. Can anyone help?

I tried reading as a JSON file but it can't read it because it is not double quoted. I tried to call out the specific index to pull out the value that correlates to the string 'airports':0

example:

noise_r = json_data['result']
t = noise_r.index('airports')

I am not familiar at all with python so I am not sure what to really try.

Upvotes: -1

Views: 114

Answers (2)

dolmok
dolmok

Reputation: 168

You can loop through the dictionary to create a table. Given that your JSON data is a list, you should loop over it to get each dictionary within it.

Use the dict.items() method when looping over a dictionary to get each key-value pairs. A typical implementation will be as follows:

data_to_make_table = json_data['result'];  # Get the list to iterate over

for dict_in_data in data_to_make_table:
    for key, value in dict_in_data.items():  # Iterate over the dictionary
        print(key, value)

If you want to store the key-value pairs as a list, you can use the items() method along with the list() function:

dict_to_make_table = {"foo": 1, "bar": 2}

result_table = list(dict_to_make_table.items())  # Make the key-value pairs as a list

print(result_table)  # [('foo', 1), ('bar', 2)]

Upvotes: -1

Hamna Rashid
Hamna Rashid

Reputation: 29

You can try this :

for key, value in noise_r[0].items():
    print(key, value)

The dictionary (json data) is inside an array. so first we take the first index of array then iterate dictionary items to view result

Upvotes: 0

Related Questions