2

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.

3 Answers 3

2

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'}}
Sign up to request clarification or add additional context in comments.

Comments

0

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"
    }
}

Comments

0
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'}
# }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.