Home > Software engineering >  Saving selected keys in a dictionary to csv
Saving selected keys in a dictionary to csv

Time:12-20

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:

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

CodePudding user response:

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)
  • Related