Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python select value on same level in json if matches

I have an api call from my python file that returns me some data in json. I want to create a list in python with all the different item ids with matching description. I made a simplified version of it below which basically shows where I am stuck currently. Also I am not sure how to ask this question so if someone has a better title please edit it.

Right now what I have thought of is saving the size of items array and loop through that but I can’t figure out how to select name value from the same level if desc_id is matching. I’m not even sure if this is the right way to do that.

json
{
  'items':[
    {
      'id': 111,
      'desc_id': 1,
    },
    {
      'id': 222,
      'desc_id': 2
    },
    {
      'id': 333,
      'desc_id': 2
    }
  ],
  'desc': [
    {
      'desc_id': 1,
      'name': 'test',
      ...
    },
    {
      'desc_id': 2,
      'name': 'something else',
      ...
    },
  ]

}

Desired output in python:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[['111', 'test', ...]['222', 'something else', ...]['333', 'something else', ...]]

>Solution :

I’d create desc as a dictionary of id: name pairs. Then when you iterate through items it’s a nested lookup of the item['desc_id']

desc = {item['desc_id']: item['name'] for item in data['desc']}

items = [[item['id'], desc[item['desc_id']]] for item in data['items']]

items
[[111, 'test'], [222, 'something else'], [333, 'something else']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading