所以我有这段代码来为api响应生成一些响应。
@app.route("/api/topFour",methods = ['POST'])
def top():
parser = request.get_json()
user_id = parser["user_id"]
item = {}
answer = []
parameters = {"user_id":user_id,"start_date":"2018-01-01","last_date":"2019-12-31"}
response = requests.post("https://my_doamin/app/api/get-customer-list",params= parameters)
data = response.json()
if data["status"] == "1":
customer_list = data["customerList"]
print(customer_list)
for i in customer_list:
item["customer_id"]= i["id"]
item["customer_name"]=i["company_name"]
print(item)
answer.extend(item)
return jsonify({"user_id":user_id,"top4user": answer})
所以在我的cmd中:这是客户列表的输出:
[{'id': 422689, 'full_name': 'jeff bezos', 'company_name': 'Amazon inc', 'create_date': '2019-03-08 17:38:48'}, {'id': 423053, 'full_name': 'akshit', 'company_name': 'HP Globalsoft pvt ltd', 'create_date': '2019-03-09 12:31:42'}, {'id': 422666, 'full_name': 'bill gates', 'company_name': 'Microsoft C
orporation', 'create_date': '2019-03-08 17:16:26'}, {'id': 423034, 'full_name': 'mukesh', 'company_name': 'Reliance Industries Limited', 'create_date': '2019-03-09 12:26:15'}]
这用于打印(项目):
{'customer_id': 422689, 'customer_name': 'Amazon inc'}
{'customer_id': 423053, 'customer_name': 'HP Globalsoft pvt ltd'}
{'customer_id': 422666, 'customer_name': 'Microsoft Corporation'}
{'customer_id': 423034, 'customer_name': 'Reliance Industries Limited'}
但是当我将其扩展到列表中时,它会给出以下响应:
{
"top4user": [
"customer_id",
"customer_name",
"customer_id",
"customer_name",
"customer_id",
"customer_name",
"customer_id",
"customer_name"
],
"user_id": 6052
}
以下是我期望的输出:
[
{'customer_id': 423034, 'customer_name': 'Reliance Industries Limited'},
{'customer_id': 423034, 'customer_name': 'Reliance Industries Limited'},
{'customer_id': 423034, 'customer_name': 'Reliance Industries Limited'},
{'customer_id': 423034, 'customer_name': 'Reliance Industries Limited'}
]
应该是词典列表!我在这里做错了什么? 我也尝试了追加。它不起作用!
答案 0 :(得分:0)
您可以尝试以下方法吗?
for i in customer_list:
item = {}
item["customer_id"] = i["id"]
item["customer_name"] = i["company_name"]
print(item)
answer.append(item)
以下是输出:
[
{'customer_id': 422689, 'customer_name': 'Amazon inc'},
{'customer_id': 423053, 'customer_name': 'HP Globalsoft pvt ltd'},
{'customer_id': 422666, 'customer_name': 'Microsoft Corporation'},
{'customer_id': 423034, 'customer_name': 'Reliance Industries Limited'}
]