How can I receive a list of dictionaries in djano?

Viewed 53

Hello I am working on a djago project and I want to recieve a list of dictionaries just like this: [{1: 20}, {2:30}, {3: 50}, ......] here the key is the id of the productand value is price And the code below is just receiving a single dictionary like this {"id": 1, "price" : 20} I want to change it to something look like I mentioned above

 list_of_objects = []
        try:
            id = int(request.payload.get("id"))
            price = int(request.payload.get("price"))
            list_of_objects.append({
                "id" : id,
                "price" : price
            })
        except ValueError:
            return response.bad_request("Invalid price, %s, should be in whole dollars" % price)



I don't know how to do it Thanks

3 Answers

Try this

        list_of_objects = []
        try:
            id = int(request.payload.get("id"))
            price = int(request.payload.get("price"))
            list_of_objects.append({
                id: price   # here changes
            })
        except ValueError:
            return response.bad_request("Invalid price, %s, should be in whole dollars" % price)

This should do the trick:

    your_dict = {}
    try:
        id = int(request.payload.get("id"))
        price = int(request.payload.get("price"))
        your_dict[id] = price
    except ValueError:
        return response.bad_request("Invalid price, %s, should be in whole dollars" % price)

This worked for me; I did the same thing a little while ago.

request_dict = dict(request.payload)

I hope it works for you too.

Related