Python新手求助:基于嵌套字典条件创建新列表返回空数组
问题排查与解决
你的代码返回空数组的原因是条件判断逻辑错误:x['type'] == 'edit' in x 会被Python按照运算符优先级解析成 (x['type'] == 'edit') and ('edit' in x)。但每个字典元素的键是'type'、'ns'等,不存在'edit'这个键,所以第二个条件永远不成立,整个判断结果一直是False,自然不会往列表里加元素。
修复方案
1. 修正循环判断逻辑
直接判断字典中'type'对应的值是否为'edit'即可:
newlist = [] for x in fruits: if x['type'] == 'edit': newlist.append(x) print(newlist)
如果担心某些字典可能没有'type'键导致报错,可以用get()方法做安全处理:
newlist = [] for x in fruits: if x.get('type') == 'edit': newlist.append(x) print(newlist)
2. 更简洁的列表推导式写法
Python里处理这种过滤场景,用列表推导式更高效简洁:
# 直接判断 newlist = [x for x in fruits if x['type'] == 'edit'] # 安全判断版本 newlist = [x for x in fruits if x.get('type') == 'edit']
运行修正后的代码,就能得到包含两个type为'edit'的字典的新列表。
内容的提问来源于stack exchange,提问作者Brie Tasi
相关产品推荐
相关产品推荐

