Python script to retrieve matching values on the same level of a JSON structure

I am facing a dilemma with my Python code that involves making an API call and receiving JSON data. My goal is to create a list in Python containing item IDs along with their matching descriptions. Below is a simplified version of the issue I am currently grappling with. Additionally, I am unsure about how to phrase this question, so any suggestions for a better title would be appreciated.

As of now, my approach involves saving the size of the items array and looping through it. However, I am struggling to extract the name value from the same level when the desc_id matches. I'm not entirely certain if this is the correct method to achieve the desired outcome.

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', ...]]

Answer №1

In my opinion, building a dictionary called desc with id: name pairs would be the most efficient approach. This way, you can easily look up names based on ids when iterating through the items list.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting JSON parsing issues in PHP

In reference to the discussion at: , where suggestions mainly revolved around JavaScript. Is there a specific function in PHP that can be utilized to address the issue described below and ensure that the output is valid JSON? Please note that using front ...

What is preventing me from accessing the JSON return values in my .NET MVC project?

I've been stuck on this seemingly minor issue for hours now. Every time I look at the console, it's showing 500 errors and nothing is coming up in alerts. It appears that the Json() function isn't working as expected. I even tried setting a ...

I am unable to remove my quotes in Django using Python

I have recently developed a Django project that allows users to submit quotes from various authors. I am facing an issue where I cannot delete quotes on the same page. The goal is for users to have the ability to delete their own quotes. <!DOCTYPE htm ...

Python: storing whole numbers in a byte-sized space

I'm exploring ways to encode 4 integers into a single byte. In the code snippet below, I manage to unpack \x11 and extract the bits (resulting in: 1 2 0 0). But how can I reverse this process? In other words, how do I pack 1 2 0 0 back into &bso ...

Using R to retrieve values from JSON lists

My knowledge in using R is limited and I need to create a script for a school project. I have a json file with nested lists, and my task is to extract values from two specific attributes. The challenge lies in the fact that these attributes are located i ...

Tips for importing a .geojson document in TypeScript using webpack?

I am trying to extract data from a .geojson file but faced some challenges while attempting two different methods: const geojson = require('../../assets/mygeojson.geojson'); The first method resulted in an error message stating: Module parse f ...

Tips on setting up virtualenv for Python 3 on a Mac

I have multiple versions of Python installed on my Mac and I want to set python3 as the default version while also using virtualenv and virtualenvwrapper. To achieve this, I created an alias in my ~/.zshrc alias python='python3' I also added t ...

Having trouble retrieving JSON value in JSP using Spring MVC, as it always returns 0

Seeking assistance with JSON string retrieval in JSP after adding it to the modelAndView. Upon debugging, I discovered that it is indeed being added to the modelAndView instance. Here's the snippet of code: Controller: modelAndView.addObject("json ...

How can I convert an xlsx file to JSON using ExcelJS in Node.js?

https://github.com/guyonroche/exceljs I am a beginner with exceljs and just came across the description of exceljs on github. The description states: "Read, manipulate and write spreadsheet data and styles to XLSX and JSON." I am looking for a way to ...

What is the JQuery code to select a checkbox and display an input field?

I have created a function that retrieves a JSON response, and the data from this response is displayed in the input fields. This is a table. When I click the edit button, it sends a request to the master_get_items file and receives the response. Table sn ...

I am interested in delivering a blended, divided response containing JSON and a string using Express

I am currently in the process of integrating ChatGPT into my Node/Express project and I have a specific requirement. I would like to initially send some metadata in JSON format to the client before streaming the response from ChatGPT as it comes in. Every ...

Adding Information to Mongodb with C#

using MongoDB.Bson; using MongoDB.Driver; protected static IMongoClient client; protected static IMongoDatabase db; public async void Insert() { client = new MongoClient(); db = client.GetDatabase("Database"); str ...

Library utilizing Python for parsing DNS data from pcap files created through the use of Wireshark

I am just starting out with Python and I have a .pcap file from Wireshark that includes a DNS query and response. My goal is to access this file, retrieve the requested hostname along with the record types and IP addresses that are returned. While explor ...

Do Python methods and functions often utilize CamelCase?

In accordance with the PEP 8 style guide for Python, it is recommended that method names be written in lowercase and may sometimes include embedded underscores. Have seasoned Python programmers encountered methods written in CamelCase (with a leading cap ...

Python implementation of Weibull distribution-based randomization

I am looking to utilize the Weibull function in order to create random numbers that fall within a specific range. Although I am aware of the scipy function weibull_min.rvs(k, loc=0, scale=lam, size=n, random_state=5), which generates a specified number of ...

Which version of mod-wsgi should be utilized with a Django stack running on Python 2.7?

Installing libapache2-mod-wsgi with Apt package manager is a straightforward process, and it typically provides mod_wsgi-3.3. However, after exploring the documentation at , I discovered that: There have been security vulnerabilities in mod_wsgi versio ...

Converting child dictionaries with identical key names to CSV format using Python's DictWriter

Looking for a solution to format JSON files into CSV files? I have a specific structure in my json file, as shown below: [ {"A":{"value":1}, "B":{"value":2}}, {"A":{"value":9}, "B":{&quo ...

How can I determine the specific quantity of XPATH links with unique identifiers in Selenium?

Seeking automation with Python3 and selenium to streamline searches on a public information site. The process involves entering a person's name, selecting the desired spelling (with or without accents), navigating through a list of lawsuits, and acces ...

Utilizing the foreach loop in PHP to display JSON data from the CoinMarket API

I am having trouble printing JSON data in a PHP foreach loop. I have tried multiple methods but nothing seems to work. The data is coming from the CoinMarket API and I am currently using the following code to print it, however, I am unable to access each v ...

Python urllib2 encounters difficulty in parsing a webpage

Currently, I am utilizing urllib2 within Python to scrape data from a webpage. However, I have encountered an issue where the read() method is not returning any results. Below is the code snippet I am using: import urllib2 url = 'http://edmonton.en ...