Python list comprehension throwing KeyError when returning key-value item on an if-else statement
The deviceResponse
field throws a KeyError as responseText
does not always exist in json_data
entries. One way to resolve this is by adding this field in if missing in any entry, but is there a way to fix the deviceResponse
field to return
- empty string if no
responseText
- entire responseText if it’s a string
- just [“responseText”][“elements”] if that exists
returned_list = [
{
"deviceResponse": i["payload"]["responseText"] if i["payload"]["responseText"] and isinstance(i["payload"]["responseText"], str) else i.get("payload", "").get("responseText", "").get("elements", ""),
"timestamps":[
{
"eventTime": i["header"]["eventTime"]["timestamp"]
}
]
}
for i in json_data if i["header"]["customer"]["id"] == customer_id
]
New contributor
Sunshine Yellow is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.