KGoed
KGoed

Reputation: 27

Trying to create a nested dictionary from pandas dataframe

I am trying to create a dictionary from a dataframe where the first column value is the key and within it other columns use a combination of the header and value to create the dictionary.

import pandas as pd

data = [
    [1,'name1', 'surname1'],
    [2,'name2', 'surname2'],
    [3,'name3', 'surname3']
]

df = pd.DataFrame(data,columns=['pkey','first_name', 'last_name'])

wanted_dictionary = {
    1 : {'first_name' : 'name1', 'last_name' : 'surname1'},
    2 : {'first_name' : 'name2', 'last_name' : 'surname2'},
    3 : {'first_name' : 'name3', 'last_name' : 'surname3'},
}

print(wanted_dictionary)

I have tried many variations using to_dict and groupby but just can't seem to crack it.

Upvotes: 2

Views: 62

Answers (3)

Laurent B.
Laurent B.

Reputation: 2263

spl = df.to_dict('split')
d = {e[0]:{spl['columns'][1]:e[1],spl['columns'][2]:e[2]} for e in spl['data']}

print(d)
# {
#  1: {'first_name': 'name1', 'last_name': 'surname1'}, 
#  2: {'first_name': 'name2', 'last_name': 'surname2'}, 
#  3: {'first_name': 'name3', 'last_name': 'surname3'}
# }

Upvotes: 0

BrokenBenchmark
BrokenBenchmark

Reputation: 19223

You can use:

df.set_index("pkey").to_dict(orient="index"))

This outputs:

{
    "1": {
        "first_name": "name1",
        "last_name": "surname1"
    },
    "2": {
        "first_name": "name2",
        "last_name": "surname2"
    },
    "3": {
        "first_name": "name3",
        "last_name": "surname3"
    }
}

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61910

Use set_index followed by to_dict:

res = df.set_index("pkey").to_dict("index")
print(res)

Output

{1: {'first_name': 'name1', 'last_name': 'surname1'},
 2: {'first_name': 'name2', 'last_name': 'surname2'},
 3: {'first_name': 'name3', 'last_name': 'surname3'}}

Upvotes: 2

Related Questions