我正在从 csv 读取 API 输入,下面是我得到的列表
[{'name': 'john', 'loan_info': [{'amount': '9000', 'rate': 12.2}]}]
在上面的列表中,我想更改顺序,即
[{'loan_info': [{'amount': '9000', 'rate': 12.2}],'name': 'john'}]
任何人都可以在这里提供帮助,在此先感谢
答案 0 :(得分:1)
您尝试做的是不是更改列表顺序,而是更改字典顺序:
Trying to swap these two, elements of a dictionary.
| |
[{'name': 'john', 'loan_info': [{'amount': '9000', 'rate': 12.2}]}]
|| ||__________dictionary__________||||
|| |______________list______________|||
||___________________________dictionary__________________________||
|_______________________________list______________________________|
字典没有内在顺序,当您添加或删除键时(并且可能在任何时间),顺序可以任意更改。
如果你想以特定的顺序显示它们,你需要明确地这样做,可能会像这样的怪物:
mylist = [{'name': 'john', 'loan_info': [{'amount': '9000', 'rate': 12.2}]}]
print(mylist)
print("\n".join([f"[{{'loan_info': {x['loan_info']}, 'name': '{x['name']}'" for x in mylist]), end="}]\n")
这给了你:
[{'name': 'john', 'loan_info': [{'amount': '9000', 'rate': 12.2}]}]
[{'loan_info': [{'amount': '9000', 'rate': 12.2}], 'name': 'john'}]
但是,考虑到该代码实际上是多么可怕(以及在不炸毁您的头骨的情况下添加字段需要付出多少努力),您可能希望选择更好的漂亮打印解决方案。< /p>
答案 1 :(得分:0)
I need to add the dict loan_info at the beginning of the list as I need to pass that in a post request to forming that API payload below is the code
The main problem is: I am reading some data from a CSV sheet below is my coded
f = pd.read_csv('/testdata.csv',
dtype={
"amount": str,
"rate": float,
"debt_type": str,
"country": str
})
finalList = []
finalDict = {}
grouped = df.groupby(['name'])
for key, value in grouped:
dictionary = {}
j = grouped.get_group(key).reset_index(drop=True)
dictionary['name'] = j.at[0, 'name']
dictList = []
anotherDict = {}
for i in j.index:
anotherDict['amount'] = j.at[i, 'amount']
anotherDict['rate'] = j.at[i, 'rate']
dictList.append(anotherDict)
print(dictList)
dictionary['loan_info'] = dictList
finalList.append(dictionary)
json.dumps(finalList)
now the list order I want to achieve is below:
[{'loan_info': [{'amount': '9000', 'rate': 12.2}],'name': 'john'}]
and the current order is
[{'name': 'john', 'loan_info': [{'amount': '9000', 'rate': 12.2}]}]