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",
}
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",
}
You can just do this:
In [1256]: df.set_index('id').to_dict()['name']
Out[1256]: {1: 'hello', 2: 'world'}
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()
)
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')
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'}}