Click here to Skip to main content
16,017,954 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have api call response as below,

x = response.json()

{'selectedColumns': [], 'totalRows': 2, 'pageNumber': 0, 'pageSize': 0, 'searchResults': 
{'items': [
{'id': '199', 'tiName': 'host-a', 'cmbMake': 'Cisco Systems', 'cmbModel': 'Catalyst C2960G-48TC-L', 'tiCustomField_CDP Neighbors': "[{'dest_host': ' AAA', 'sysname': ''}, {'dest_host': ' BBB', 'sysname': ''}]"}, 
{'id': '1504', 'tiName': 'host-b', 'cmbMake': 'Cisco Systems', 'cmbModel': 'Catalyst C2960-48TC-L', 'tiCustomField_CDP Neighbors': "[{'dest_host': ' CCC', 'sysname': ''}, {'dest_host': ' DDD', 'sysname': ''}]"}
]}}


What I have tried:

y = x['searchResults']['items']

keys = {"tiCustomField_CDP Neighbors","id"}
res = {}
l = []
for i in y:
    for k, v in i.items(): 
        if k in keys:
            sub = {k: v}
            res.update(sub)
            l.append(res)
out = l
print(out)  


based on above code i am getting output as:

[{
    "id": "1504",
    "tiCustomField_CDP Neighbors": "[{'dest_host': ' CCC', 'sysname': ''}, {'dest_host': ' DDD', 'sysname': ''}]"
},
{
    "id": "1504",
    "tiCustomField_CDP Neighbors": "[{'dest_host': ' CCC', 'sysname': ''}, {'dest_host': ' DDD', 'sysname': ''}]"
}]


the way i wanted is:

[
    {
        "id": "199",
        "tiCustomField_CDP Neighbors": "[{'dest_host': ' AAA', 'sysname': ''}, {'dest_host': ' BBB', 'sysname': ''}]"
    },

    {
        "id": "1504",
        "tiCustomField_CDP Neighbors": "[{'dest_host': ' CCC', 'sysname': ''}, {'dest_host': ' DDD', 'sysname': ''}]"
    }
]


Please any one suggest the right way of for loop so that i get above output.

i am running python3. also i am new to python. still trying to learn it.apologies for any mistakes that i did.
Posted
Updated 28-Jan-22 13:52pm
v2

1 solution

vr20222,

It's much simpler that what you have produced...

Python
my_keys = {"id","tiCustomField_CDP Neighbors"}
res = {}
l = []

for i in y:
  res = {my_key:i[my_key] for my_key in my_keys}
  l.append(res)
  
print(l)


You'll note that I reversed the order of the 'my_keys' var. This way, the 'id' key is appended first.

Hope this helps!
 
Share this answer
 
Comments
vr20222 28-Jan-22 22:46pm    
Thank you Manuel, your solution worked.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900