Reputation: 1420
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
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
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
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