我希望创建一个从API返回的所有错误的字符串。列表中可能会返回多个错误。每个错误都是一个字典,我希望访问它的字符串:
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 errors in result:
for error in errors:
returned_string += " {}".format(error['reason'])
有更多的pythonic方式吗?
答案 0 :(得分:4)
您的代码中存在多个拼写错误。但是使用 list comprehension 生成器表达式的Pythonic方式更多:
return_string = ""
if "errors" in result:
return_string = " ".join(error['reason'] for error in result['errors'])
甚至在一行中:
return_string = " ".join(error['reason'] for error in result.get('errors', []))
答案 1 :(得分:0)
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
<强>输出:强>
the inputted date field does not match required format
the inputted message field does not match required format
答案 2 :(得分:0)
您可以使用operator.itemgetter
和map
从您的字典列表中获取reason
密钥,例如
>>> from operator import itemgetter
>>> error_list = list(map(itemgetter('reason'),r['errors']))
这将为您提供类似
的输出>>> ['the inputted date field does not match required format', 'the inputted message field does not match required format']
接下来,您可以使用join
将这些字符串连接在一起作为一条错误消息
>>> "".join(error_list)
>>> 'the inputted date field does not match required formatthe inputted message field does not match required format'
您还可以指定要分隔这两个字符串的字符
>>> " ".join(error_list) #Whitespace
>>> 'the inputted date field does not match required format the inputted message field does not match required format'
如果你喜欢单行
>>> " ".join(map(itemgetter('reason'),r['errors']))