PVR
PVR

Reputation: 1

Python Pandas : Nested Dictionaries

I have created DataFrame, Check below snippet.

data = {'mapid': [101,102],
        'mapname': ['xyz','xyy'],
        'xaxis' : [41,42],
        'yaxis' : [42,32]
        }
        
df = pd.DataFrame(data, columns = ['mapid', 'mapname','xaxis','yaxis'])```

Output of Dataframe.

``print(df)

mapid mapname  xaxis  yaxis
101     xyz     41     42
102     xyy     42     32

Here i just want to create nested dictionary from this DataFrame.

Expected output

enter image description here

{'101':{'mapname':'xyz'
            'data' : ['xaxis' : 41,'yaxis':42]}}

I have tried below code getting expected output still i'm unable to figure it out. Please help me out here.

#Tried Snippet
**code**

print({n: grp.loc[n].to_dict('index')for n, grp in df.set_index(['mapid', 'mapname']).groupby(level='mapid')})

**output**

{101: {'xyz': {'xaxis': 41, 'yaxis': 42}}, 102: {'xyy': {'xaxis': 42, 'yaxis': 32}}}

**code**

print({k:f.groupby('mapname')['xaxis'].apply(list).to_dict() for k, f in df.groupby('mapid')})

**output**

{101: {'xyz': [41]}, 102: {'xyy': [42]}}

Upvotes: 0

Views: 61

Answers (1)

Ali Zaini
Ali Zaini

Reputation: 88

You cannot have ['xaxis' : 41,'yaxis':42] as it has to be a dictionary. I assume you mean {"101": {"mapname": "xyz", "data": {"xaxis": 41, "yaxis": 42}}}

Probably not the best solution but

{i:{"mapname": j,"data":k} for (i,j),k in df.set_index(["mapid","mapname"]).to_dict(orient="index").items()}

seems to work

Upvotes: 1

Related Questions