Home > database >  Python select value on same level in json if matches
Python select value on same level in json if matches

Time:04-04

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:

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

CodePudding user response:

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']]
  • Related