Generating a nested list structure from a dictionary with varying levels of nesting

I am working with a dictionary obtained from a cURL call in Python 3.8 and my goal is to extract information from just two specific keys to create a list that can be written into a csv file.

The dictionary contains only one key-value pair, where the value is a list of dictionaries that hold the desired information. In these nested dictionaries, I am specifically interested in the 'conceptId' and 'fsn' key-value pairs (with 'fsn' further containing another nested dictionary from which I need the 'term').

Below is an excerpt of the dictionary featuring two relevant 'items', despite its actual size being much larger.

res_json = {'items': [{'conceptId': '15964901000119107', 'active': True, 'definitionStatus': 'PRIMITIVE', 'moduleId': '900000000000207008', 'fsn': {'term': 'Atypical atrial flutter (disorder)', 'lang': 'en'}, 'pt': {'term': 'Atypical atrial flutter', 'lang': 'en'}, 'id': '15964901000119107'}, {'conceptId': '10811961000119109', 'active': True, 'definitionStatus': 'FULLY_DEFINED', 'moduleId': '900000000000207008', 'fsn': {'term': 'Cardiac arrest due to incomplete miscarriage (disorder)', 'lang': 'en'}, 'pt': {'term': 'Cardiac arrest due to incomplete miscarriage', 'lang': 'en'}, 'id': '10811961000119109'}]}

Desired Output:

output = ['15964901000119107', 'Atypical atrial flutter (disorder)'], ['10811961000119109', 'Cardiac arrest due to incomplete miscarriage (disorder)']

Here is the code I have developed so far (flatten_json):


#Flatten json 
def flatten_json(y):
    out = {}

    def flatten(x, name=''):
        if type(x) is dict:
            for a in x:
                flatten(x[a], name + a + '_')
        elif type(x) is list:
            i = 0
            for a in x:
                flatten(a, name + str(i) + '_')
                i += 1
        else:
            out[name[:-1]] = x

    flatten(y)
    return out



flat = flatten_json(res_json)
json_normalize(flat)
output_list = []

for k, v in flat.items():
    if "conceptId" in k:
        output_list.append(v)
    if "fsn_term" in k:
        output_list.append(v)
        
for k, v in flat.items():
    if "fsn" in l:
        output[k] = v

Although the current code returns a single list with values in alternating order, it does not generate a list of lists that can be directly exported to a csv file.

>>>output_list: ['15964901000119107', 'Atypical atrial flutter (disorder)', '10811961000119109', 'Cardiac arrest due to incomplete miscarriage (disorder)']

How can I enhance the functionality of my existing code?

Answer №1

In order to streamline the process, I found that creating a simplified dictionary containing only the 'items' values - a list of dictionaries. Afterward, it was easy to access the specific key-value pairs needed and compile them into a new list.

my_items = {}

    for key, value in response_json.items():
        if key == 'items':
            my_items[key] = value
        
result = sorted([[item['conceptId'], item['fsn']['term']] for item in my_items['items']])

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

Utilizing Javascript to Extract Data from Twitter Json Files

Can someone provide assistance with parsing JSON feed text retrieved from Twitter? I am looking to access and apply style tags to elements like the link, created date, and other information. Any tips on how I can achieve this task successfully would be g ...

Is it acceptable to replicate another individual's WordPress theme and website design in order to create my own WordPress website that looks identical to theirs?

It may sound shady, but a friend of mine boasts about the security of his WordPress website, claiming it's impossible to copy someone else's layout or theme. However, my limited experience in web development tells me otherwise. I believe it is po ...

Why is the toggle list not functioning properly following the JSON data load?

I attempted to create a color system management, but as a beginner, I find it quite challenging! My issue is: When I load my HTML page, everything works fine. However, when I click on the "li" element to load JSON, all my toggle elements stop working!!! ...

The many potentials of looping through Sass maps

My sass map contains a variety of color shades, and the full code can be found on Codepen: $pbcolors: ( pbcyan : ( 50: #E5F5FC, 100: #CCEBF9, 200: #99D7F2, 300: #66C3EC, 400: #33AFE5, 500: #009DBF, 600: #008CAB, 700: #007C98, 800: #006D85, 900: #005D72 ...

Modifying the color of a variety of distinct data points

There was a previous inquiry regarding Changing Colour of Specific Data, which can be found here: Changing colour of specific data Building upon that question, I now have a new query. After successfully changing the 2017 dates to pink, I am seeking a way ...

Trouble displaying data in Jquery JSON

I've been on the hunt for hours, trying to pinpoint where the issue lies within my code. Despite scouring different resources and sites, I can't seem to figure it out. Whenever I click "Get JSON Data," nothing seems to display below. Can someone ...

fullcalendar adjusting color while being moved

Currently, I have implemented a fullcalendar feature that displays entries for multiple users with different colored calendars. However, there seems to be an issue when dragging an entry to another date - the color reverts back to default. Below is an exa ...

Retrieve jQuery CSS styles from a JSON database

I've been attempting to pass CSS attributes into a jQuery method using data stored in a JSON database. However, it doesn't seem to be functioning as expected. I suspect that directly inputting the path to the JSON variable may not be the correct ...

CSS background image referencing in React to the public folder's path

I am currently working on a project using Create-React-App and I am trying to set a background image for my header section. Here is how I'm attempting to do it: background-image: url('~/Screenshot_11.png'); However, I encountered an error w ...

What is the process of using an if statement in jQuery to verify the existence of a property in a JSON file?

I am working on a task to incorporate an if statement that checks for the existence of a specific property in a JSON file. If the property exists, I need to display its value within HTML tags <div class='titleHolder'> and "<div class=&ap ...

Is there a way to open an HTML file within the current Chrome app window?

Welcome, My goal is to create a Chrome App that serves as a replacement for the Chrome Dev Editor. Here is my current progress: background.js chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('backstage.html', { ...

How can I update my outdated manifest v2 code to manifest v3 for my Google Chrome Extension?

Currently, I am developing an extension and using a template from a previous YouTube video that is based on manifest v2. However, I am implementing manifest v3 in my extension. Can anyone guide me on how to update this specific piece of code? "backgro ...

Boundaries on Maps: A guide to verifying addresses within a boundary

User provides address on the website. If the address falls within the defined boundary, it is marked as "Eligible". If outside the boundary, labeled as "Ineligible". Are there any existing widgets or code snippets available to achieve this functio ...

What is the best way to add custom styles to an Ext JS 'tabpanel' xtype using the 'style

Is there a way to change the style of a Ext.tab.Panel element using inline CSS structure like how it's done for a xtype: button element? { xtype: "button", itemId: "imageUploadButton1", text: "Uploader", style: { background : ' ...

Creating two columns using React and Material-UI Grid while utilizing just one map function for iteration

I am facing a challenge with Material-UI Grid. I want to display the information from my map function in two columns instead of one. I tried adding another Grid item sm={6} and using the same map function, which resulted in two columns but with identical i ...