Python新手求助:如何直接生成字典列表而非先返回字典?
直接生成目标字典列表的方法
首先先修正你原函数里的两个明显问题:
- 循环遍历
response时,你错误地使用了response["Status"],应该用当前循环项res["Status"] - 全局变量
nodes容易导致后续调用函数时出现数据残留的问题,建议把容器定义在函数内部
当然可以直接在函数里生成你要的字典列表,不需要先做普通字典再转换。直接在循环中构造符合格式的字典,添加到列表即可:
只保留Status为Pass的项(和原函数逻辑一致)
def populateItems(response): nodes_list = [] for res in response: if res["Status"] == "Pass": nodes_list.append({"Id": res["key"], "value": res["Status"]}) return nodes_list
保留所有状态(包括Fail)
如果需要保留所有条目,去掉if判断即可:
def populateItems(response): nodes_list = [] for res in response: nodes_list.append({"Id": res["key"], "value": res["Status"]}) return nodes_list
更简洁的列表推导式写法
熟悉Python后,可以用列表推导式简化代码,逻辑和上面完全一致:
# 只保留Pass的情况 def populateItems(response): return [{"Id": res["key"], "value": res["Status"]} for res in response if res["Status"] == "Pass"] # 保留所有状态的情况 def populateItems(response): return [{"Id": res["key"], "value": res["Status"]} for res in response]
内容的提问来源于stack exchange,提问作者Sudha N
相关产品推荐
相关产品推荐

