user7692855
user7692855

Reputation: 1420

Concatenate String in Python

I am looking to create a string of all errors returned from the API. There may be multiple errors returned in a list. Each error is a dict and the string I wish to access its the reason:

  result: {
       errors: [{
          error: 'invalid_input',
          code: 409,
          reason: 'the inputted date field does not match required format'

       },
       {
          error: 'invalid_input',
          code: 409,
          reason: 'the inputted message field does not match required format'
        }

  }

What I have tried is:

return_string = ""
if errors in result:
    for error in errors:
        returned_string += " {}".format(error['reason'])

Is there a more pythonic way to do it?

Upvotes: 0

Views: 116

Answers (3)

Thomas
Thomas

Reputation: 181705

There are several typos in your code. But the more Pythonic way would be with a list comprehension generator expression:

return_string = ""
if "errors" in result:
    return_string = " ".join(error['reason'] for error in result['errors'])

Or even in one line:

return_string = " ".join(error['reason'] for error in result.get('errors', []))

Upvotes: 4

Sohaib Farooqi
Sohaib Farooqi

Reputation: 5666

You can use operator.itemgetter along with map to fetch the reason key from your list of dicts like

>>> from operator import itemgetter
>>> error_list = list(map(itemgetter('reason'),r['errors']))

This will give you output like

>>> ['the inputted date field does not match required format', 'the inputted message field does not match required format']

Next you can use join to join these strings together as one error message

>>> "".join(error_list)
>>> 'the inputted date field does not match required formatthe inputted message field does not match required format'

You can also specify the character on which you want seperate these two string

>>> " ".join(error_list) #Whitespace
>>> 'the inputted date field does not match required format the inputted message field does not match required format'

If you prefer one-liners

>>> " ".join(map(itemgetter('reason'),r['errors']))

Upvotes: 0

Rakesh
Rakesh

Reputation: 82755

result = {
       "errors": [{
          "error": 'invalid_input',
          "code": 409,
          "reason": 'the inputted date field does not match required format'

       },
       {
          "error": 'invalid_input',
          "code": 409,
          "reason": 'the inputted message field does not match required format'
        }]

  }

return_string = ""
if result.get("errors", None):
    for error in result["errors"]:
        return_string += " {}\n".format(error['reason'])
print return_string

Output:

the inputted date field does not match required format
 the inputted message field does not match required format

Upvotes: 0

Related Questions