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

Saving selected keys in a dictionary to csv

I have a dictionary in python whose output is:

out = {
            "lower_level": {
                i: {"name": j["name"], "confidence": j["prob"], "by": 1}
                for i, j in level4.items()
            },
        }

This out dict is a list of Dict.

I want to save this dictionary in the form of following csv:

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

query category confidence
i     name      prob

How can i do this?

Sample out dict:

{'lower_level': {'television': {'name': '8k smart television', 'confidence': 0.9041114449501038, 'by': 1}}}

Desirec output in csv:

query      category      confidence
television 8k smart tv   0.9041

>Solution :

Create list of nested dictionaries, add query and pass to DataFrame constructor, last remove column by and rename column name:

out = {'lower_level': {'television': {'name': '8k smart television', 
                                      'confidence': 0.9041114449501038, 'by': 1}}}
                    
df = (pd.DataFrame([{**{'query': k1},**v1} for k, v in out.items() for k1, v1 in v.items()])
        .drop('by', axis=1)
        .rename(columns={'name':'category'}))
print (df)
        query             category  confidence
0  television  8k smart television    0.904111

Or if possible generate list of dict from level4:

L = [{"query":i,"category":j["name"],"confidence":j["prob"]} for i,j in level4.items()]
df = pd.DataFrame(L)

df.to_csv('file', index=False)
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