无法将字典合并到列表中

Not able to merge dictionaries into a list

所以我有这段代码可以为 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'}
]

应该是字典列表。我试过追加。

edit: 那是我初学的时候,很沮丧。请在评论中提供反馈,而不仅仅是增加消极性。我想帮助改进更好。

你可以尝试以下方法吗:

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'}
]