Невозможно объединить словари в список - PullRequest
0 голосов
/ 02 апреля 2019

Итак, у меня есть этот фрагмент кода, чтобы сгенерировать некоторый ответ для ответа 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'}
]

Это должен быть список словарей! Что я тут не так делаю?я попробовал с добавлением, а также.это не работает!

1 Ответ

0 голосов
/ 02 апреля 2019

Можете ли вы попробовать следующее:

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'}
]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...