Gaurav Agrawal
Gaurav Agrawal

Reputation: 131

List Comprehension with IF clause

Why below code is not working with IF condition in list comprehension? "Contents" does not exist in "response" to it should return empty list.

response={"Contents1" : [ {"a" : 1, "b" : 1},{"a" : 2, "b" : 2},{"a" : 3, "b" : 3 } ] }
lst=[item["a"] for item in response["Contents"] if "Contents" in response]
print(lst)

KeyError: 'Contents'

Below works fine and does not print any output as "Contents" does not exist in "response"

if "Contents" in response:
    for item in response["Contents"]:
    print(item["a"])

Upvotes: 1

Views: 89

Answers (1)

John Coleman
John Coleman

Reputation: 52008

The comprehension is still trying to access a dictionary with a non-existent key. You could do the following instead:

[item["a"] for k in response for item in response[k] if k == "Contents"]

Upvotes: 1

Related Questions