kemosabee kemosabee - 1 year ago 47
PHP Question

how to avoid typeerror while returning result from php to python

I have the following code in php and python,I return $result from php to a python handler and running into below should I return in python so that I don't run into this error?


$result = [
"PW_LINK" => ""


orderedResults = sorted(result['result'].items(), key=lambda kv: kv[1]['Order'])


File "\\data\workspace\username\pwp4plugin\", line 269, i
n <lambda>
orderedResults = sorted(result['result'].items(), key=lambda kv: kv[1]['Orde
TypeError: string indices must be integers, not str

Answer Source

The issue is with kv[1]['Order'] being passed to the lambda function being passed to key. Assuming the dict which Python has after doing json.decode() is this:

>>> result = {'result': {
...                      "TRIGGER_STATUS": "SUCCESS",
...                      "PW_LINK": ""
...                      }
...           }
>>> # this is what .items() looks like:
... result['result'].items()

So in the loop, index 1 is '' and 'SUCCESS':

>>> for kv in result['result'].items():
...   print kv[1]
  1. So kv[1]['Order'] is attempting to lookup a key called 'Order' against each of the two strings. Whereas, what Python is expecting is an integer index to something in each of those strings. Example:

    >>> for kv in result['result'].items():
    ...   print kv[1][4]  # the fifth letter in each string
  2. In the PHP associative array you've given, there is no key 'Order'. So it's unclear to us what you were trying to use. What is result in Python once the PHP result is parsed?