I am trying to parse info (from "result") from an HTTP API which is in a list of dictionaries. How can I iterate to parse only the following values from all dictionaries?
"a_name":
"ch":
"e":
[
{
"2H": {
"time": 156450,
"n_ap": 10,
"n_rad": 9,
"xyz": {
"is_c": false,
"is_d": false,
"num_a": 0,
"num_d": 0
},
"o_time": 276,
"q_t": 16,
"result": [
{
"a_name": "abc",
"ch": 2,
"e": 12,
"s_f_list": {
"b_l": [
"C20"
],
"ch_l": {
"CW160": [],
"CW20": [
1,
6,
11
],
"CW4": [],
"CW8": []
}
},
"s_id": "2z"
},
{
"a_name": "abcd",
"ch": 3,
"e": 13,
"s_f_list": {
"b_l": [
"C20"
],
"ch_l": {
"CW160": [],
"CW20": [
1,
6,
11
],
"CW40": [],
"CW80": []
}
},
"s_id": "2z"
},
.
.
.
.
.
I have tried the following code but I'm able to parse only first value. I'm new to python so if anyone here could help with this I would be very thankful.
import requests
url = "https://....."
response = requests.get(url)
data = response.json()
a_name = data[0]["2H"]["result"][0]["a_name"]
ch =data[0]["2H"]["result"][0]["ch"]
print(a_name)
print(ch)
output I received is : abc 2
Expected output:
a_name= abc ,ch = 2,e = 12
a_name= abcd ,ch = 3,e = 13
a_name= abcde ,ch = 4,e = 14
.
.
I'm new to python so if anyone here could help with this I would be very thankful.
1 Answer 1
You could use a generator and a list comprehension that contains a nested dictionary comprehension. Not tested btw.
def gen_get_items(d, keys_list):
for s in keys_list:
if s in d.keys():
yield s, d[s]
result_keys = ["aname", "ch", "e"]
results = data[0]["2H"]["result"]
specific_results = [
{k: v for k, v in gen_get_items(r, result_keys)}
for r in results
]
for specific_result in specific_results:
print(specific_result)
-
Glad to hear it! Do try to remember to mark answers as accepted if they fulfil your question (I see you’re a newish user so thought I’d give you a heads up about this).dijksterhuis– dijksterhuis08/04/2019 00:39:59Commented Aug 4, 2019 at 0:39
Explore related questions
See similar questions with these tags.