min2bro
min2bro

Reputation: 4638

Pandas dataframe to dictionary with ID as Key

Below is my pandas dataframe, Now I want to create the dictionary out of this so that a dictionary of records, where the keys are record_ids and the values are dictionaries with the keys being field names, Something Like this:

I have used df.to_dict() function but not sure how to make record_ids as key using this.

{123342: {'Address': 'Brunswick',
  'Id': '123342',
  'Name': 'Rachels Hunt',
  'Unname': 'VB INDUSTRIES',
  'no': '6032',
  'zip': '01123'}}

Dataframe

Upvotes: 2

Views: 3014

Answers (3)

Ramin Melikov
Ramin Melikov

Reputation: 1005

dict = [
    {
        d['Id']: {
            'Address'   : d['Address'],
            'Id'        : d['Id'],
            'Name'      : d['Name'],
            'Unname'    : d['Unname'],
            'no'        : d['no'],
            'zip'       : d['zip']
        }
    } 
    for d in df.to_dict(orient = 'records')
]

Upvotes: 0

Scott Boston
Scott Boston

Reputation: 153510

Let use set_index and to_dict():

df.set_index(df.Id).T.to_dict()

Output:

{123342: {'Address': 'Brunswick',
  'Id': 123342,
  'Name': 'Rachels Hunt',
  'Unname': 'VB INDUSTRIES',
  'no': 6032,
  'zip': 1123}}

Note: I am not moving the Id column into the index, but I am creating a new index identical to the Id column.

Where

print(df)

       Id    Address          Name         Unname    no   zip
0  123342  Brunswick  Rachels Hunt  VB INDUSTRIES  6032  1123

Edit for comment below:

df.apply(lambda x: x.astype(str)).set_index(df.Id).T.to_dict()

output:

{123342: {'Address': 'Brunswick',
  'Id': '123342',
  'Name': 'Rachels Hunt',
  'Unname': 'VB INDUSTRIES',
  'no': '6032',
  'zip': '1123'}}

Upvotes: 3

BENY
BENY

Reputation: 323366

Dict to dataframe

pd.DataFrame(d).T
Out[836]: 
              Address      Id          Name         Unname    no    zip
123342  Brunswick  123342  Rachels Hunt  VB INDUSTRIES  6032  01123

Dataframe to Dict

EDIT :

df.T.to_dict()
Out[850]: 
{123342: {'Address': 'Brunswick',
  'Id': '123342',
  'Name': 'Rachels Hunt',
  'Unname': 'VB INDUSTRIES',
  'no': '6032',
  'zip': '01123'}}

Upvotes: 1

Related Questions