I am creating a Python dictionary from a dataframe and the results contain a few thousand entries;
我正在从一个dataframe创建一个Python字典,结果包含几千个条目;
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.
这样做的原因是我需要将字典作为JSON传递给Web API。
Any suggestions?
有什么建议吗?
2 个解决方案
#1
1
If you really want a json you should use the method 'to_json' of DataFrames:
如果你真的想要一个json,你应该使用DataFrames的方法“to_json”:
df.to_json().
df.to_json()。
Here the documentation: pandas.DataFrame.to_json
这里的文档:pandas.DataFrame.to_json
#2
0
Your title seems misleading. If I didn't misunderstand, you want get a format of dictionary from DataFrame.
你的标题似乎误导。如果我没理解错的话,你需要从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'}]
#1
1
If you really want a json you should use the method 'to_json' of DataFrames:
如果你真的想要一个json,你应该使用DataFrames的方法“to_json”:
df.to_json().
df.to_json()。
Here the documentation: pandas.DataFrame.to_json
这里的文档:pandas.DataFrame.to_json
#2
0
Your title seems misleading. If I didn't misunderstand, you want get a format of dictionary from DataFrame.
你的标题似乎误导。如果我没理解错的话,你需要从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'}]