Home > Mobile >  Appending all for loop dicts into single list
Appending all for loop dicts into single list

Time:10-16

I just learnt django and I am getting data from api and looping through the json and appending the data into the list. but When I use .map() function in react then the data is appending in list (from for loop) like

[
    {
        "results": {
            "id": 544,
            "name": "User_1",
        }
    },
    {
        "results": {
            "id": 218,
            "name": "User_2",
        }
    },
    {
        "results": {
            "id": 8948,
            "name": "User_3",
        }
    },
    {
        "results": {
            "id": 9,
            "name": "User_4",
        }
    },
]

It is not appending like (Like I want)

[
    results : [
        {
           "id": 544,
           "name": "User_1"
        },
        {
           "id": 218,
           "name": "User_2"
        },
        {
           "id": 8948,
           "name": "User_3"
        },
        {
           "id": 9,
           "name": "User_4"
        }
    ]
]

views.py

def extract_view(request):
    results_list = []

    // api url for explanation only
    get_response = "https://api.punkapi.com/v2/beers"

    if get_response.status_code == 200:
        for result in get_response.json():
            results_list.append({"results": result})

    results_list.append({"length_of_results": len(results_list)})

    return Response({"data": results_list})

I know, In for loop it is appending every result within it with every iteration but I also want to assign all the responses within results list. Because I will add a append another field after for loop.

I have tried many times but it is still not working.

CodePudding user response:

By doing

results_list.append({"results": result})

you are creating a new dictionary with the value being result which I believe is a dictionary itself. So you should be able to just do this:

if get_response.status_code == 200:
    for result in get_response.json():
        results_list.append(result)

CodePudding user response:

You can solve it by map function iterating over list:

dict(results=list(map(lambda x: x["results"], response)))

Full working example:

response = [
    {
        "results": {
            "id": 544,
            "name": "User_1",
        }
    },
    {
        "results": {
            "id": 218,
            "name": "User_2",
        }
    },
    {
        "results": {
            "id": 8948,
            "name": "User_3",
        }
    },
    {
        "results": {
            "id": 9,
            "name": "User_4",
        }
    },
]

dict(results=list(map(lambda x: x["results"], response)))

>> [{'id': 544, 'name': 'User_1'},
>>  {'id': 218, 'name': 'User_2'},
>>  {'id': 8948, 'name': 'User_3'},
>>  {'id': 9, 'name': 'User_4'}]
  • Related