3

I have a pandas DataFrame with 2 columns. How can I convert this into a Python dictionary with id as key and name as value?

INPUT

id | name
1  | hello
2  | world

REQUIRED OUTPUT

{
    "1": "hello",
    "2": "world",
}
1

5 Answers 5

4

You can just do this:

In [1256]: df.set_index('id').to_dict()['name']
Out[1256]: {1: 'hello', 2: 'world'}
Sign up to request clarification or add additional context in comments.

Comments

2

zip the two columns you want.

dict(zip(df['id'].astype(str), df['name']))
#{'1': 'hello', '2': 'world'}

If you want to use the pandas methods, make things strings then set the keys to your index and grab the column you want to be the values and go with .to_dict

(df.astype('str')
   .set_index('id')['name']
   .to_dict()
)

2 Comments

df.astype('str') won’t make the index values strings.
In the example both 'id' and 'name' are columns so it will. You can see in my second example I then set the index to be 'id' as it's not to begin with.
1

Let us do

d=dict(zip(df.id,df.name))

Comments

1

Please try:

dict_ = {}
for  i , value in enumerate(df[‘name’]):
    dict_[i] = value

You can also try:

dict_ = df.set_index('id').to_dict()['name']

If you want dictionary value as list:

dict_ = df.set_index('id').T.to_dict('list')

1 Comment

Do you know if there is a way without loops/enumeration?
1

Other answers focus on the conversion from pandas DataFrame to dict, however the question is also about having the index values as strings.

The solution for that is to map the index to str beforehand :

df.to_dict()
{'name': {0: 'hello', 1: 'world'}}

df.index = df.index.map(str)
df.to_dict()
{'name': {'0': 'hello', '1': 'world'}}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.