1

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 Answers3

1

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)

CPMaurya
  • 371
  • 3
  • 9
1

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)
Mohsen Hassani
  • 101
  • 1
  • 5
  • This is the error: "argument must be a string, a bytes-like object or a number, not 'NoneType'" – Noor Ibrahim Feb 25 '22 at 09:49
  • I want to send dictionary like this ```{id: price, id: price, ....}``` – Noor Ibrahim Feb 25 '22 at 09:50
  • The error is because the `payload` dictionary doesn't have `id` or `price`. you can make it safer using: `id = int(request.payload.get("id"), "")` – Mohsen Hassani Feb 25 '22 at 10:04
  • I don't understand what you mean exactly. If you want your prices to be exactly like this `{id: price, id: price, ....}`, then you should have all your `price`s and `id`s and then convert them to dictionary. but with getting `id` and `price` from `payload`, you only have one item to convert to dictionary. – Mohsen Hassani Feb 25 '22 at 10:07
1

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.

Djangodev
  • 450
  • 3
  • 17