OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

List comprehension returning dictionary with if else statement for a returned key

  • Thread starter Thread starter Sunshine Yellow
  • Start date Start date
S

Sunshine Yellow

Guest
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

Code:
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
]
<p>Python list comprehension throwing KeyError when returning key-value item on an if-else statement</p>
<p>The <code>deviceResponse</code> field throws a KeyError as <code>responseText</code> does not always exist in <code>json_data</code> 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 <code>deviceResponse</code> field to return</p>
<ul>
<li>empty string if no <code>responseText</code></li>
<li>entire responseText if it's a string</li>
<li>just ["responseText"]["elements"] if that exists</li>
</ul>
<pre><code>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
]
</code></pre>
 

Latest posts

Top