将数据帧转换为排除ID的字典



我的目标是创建一个嵌套字典,但我得到了随机数作为父关键字。这就是我迄今为止所做的:

result = result[['column1', 'column2','column3']]
result = result.to_dict('index')
all_result = {'ERR_CODE' : 0, 'ERR_MESSAGE' :'No error'}
all_result['LOC'] = result

我收到的结果:

{
"ERR_CODE": 0,
"ERR_MESSAGE": "No error",
"LOC": {
"792": {  #random number or possibly the row id
"column1": "abc",
"column2": "123",
"column3": "def"
}
}
}

预期结果:

{
"ERR_CODE": 0,
"ERR_MESSAGE": "No error",
"LOC": {
"column1": "abc",
"column2": "123",
"column3": "def"
}
}

在这种情况下,我不能使用pop(792),因为数字是随机的。有什么方法可以使用索引使用pop吗?或任何其他替代方案。。

UPDATE给出的答案解决了上述问题,但如果结果下面有多个子项,例如(预期结果(:

{
"ERR_CODE": 0,
"ERR_MESSAGE": "No error",
"LOC": {
"column1": "abc",
"column2": "123",
"column3": "def"
},
{
"column1": "abc",
"column2": "123",
"column3": "def"
}
}

我根据[0:]的解决方案进行了更改,因为它给了我这个:

{
"ERR_CODE": 0,
"ERR_MESSAGE": "No error",
"LOC": [                    # list
{
"column1": "abc",
"column2": "123",
"column3": "def"
},
{
"column1": "abc",
"column2": "123",
"column3": "def"
}
]                           #list
}

我不希望结果中出现[ ]

您可以将记录作为列表分配返回

result = list(result.to_dict("index").values())

最新更新