2

I am creating a Python dictionary from a dataframe and the results contain a few thousand entries;

oxford_english = df.set_index('id')['name'].to_dict()
# Example result:
{12345: 'companyA'}

I need to convert the dictionary by changing the current keys and values into the following format:

{"id": "12345", "name": "CompanyA"}

I know how to change values and keys in a dictionary but I can't figure out how to split the entries into new key value pairs.

The reason for all of this is because I need to pass the dictionary as JSON to a Web API.

Any suggestions?

1

2 Answers 2

1

If you really want a json you should use the method 'to_json' of DataFrames:

df.to_json().

Here the documentation: pandas.DataFrame.to_json

Sign up to request clarification or add additional context in comments.

2 Comments

That was it! Thank you! I couldn't figure out, via the docs if I can select only certain columns from the DF to convert to JSON. Am I missing it? I am dumping the desired columns to a new DF as a work around.
You could just create a dataframe with the desired columns from the original: newdf = df.iloc[:, 0:5] (here i get the columns from 0 to 5). Then use the method with the new dataframe.
0

Your title seems misleading. If I didn't misunderstand, you want get a format of dictionary from DataFrame.

In [25]: df = pd.DataFrame({'id':[12345, 12346], 'name': ['CompanyA', 'CompanyB
    ...: ']})

In [26]: df
Out[26]:
      id      name
0  12345  CompanyA
1  12346  CompanyB
In [29]: df.to_dict(orient='records')
Out[29]: [{'id': 12345, 'name': 'CompanyA'}, {'id': 12346, 'name': 'CompanyB'}]

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.