Home > Net >  How can I receive a list of dictionaries in djano?
How can I receive a list of dictionaries in djano?

Time:02-25

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

CodePudding user response:

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

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

I hope it works for you too.

CodePudding user response:

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)

CodePudding user response:

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)
  • Related