Filtering dictionary of Response objects by value

Question:

I have my response dictionary.

Example:

{10874: <Response [400]>, 11233: <Response [400]>, 13360: <Response [400]>, 15008: <Response [400]>, 11638: <Response [200]>, 14150: <Response [400]>, 15323: <Response [400]>, 14814: <Response [400]>, 12007: <Response [400]>, 11337: <Response [400]>, 13342: <Response [200]>}

I’m trying to create new dictionary with only response 200.

My code:

new_dict = {}
for k,v in results.items():
    if v == "<Response [200]>":
        new_dict[k] = v

But I’m not able to filter. Type of dictionary value is class ‘requests.models.Response’.

Asked By: My80

||

Answers:

Filter Response objects by their status_code attribute:

new_dict = {k:resp for k,resp in results.items() if resp.status_code == 200}
Answered By: RomanPerekhrest
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.