Python:使用字典推导式过滤时如何移除生成的空字典?
问题原因
你当前的代码错误地把筛选条件放在了字典推导式内部,而字典推导式的作用是过滤字典中的键值对,不是过滤整个字典是否加入列表。当item['order'] < limit不成立时,字典推导式会生成一个空字典,而你不管这个字典是否为空都直接添加到cast_limit列表里,所以结果中会出现空字典。
另外你的示例desired_result包含了order=1的条目,说明你的条件应该是order <= limit而非order < limit,这是代码里的一个小疏漏。
解决方法
你需要先判断整个字典是否符合条件,只有符合条件的字典才添加到列表中——这里不需要用字典推导式,因为你要保留字典的所有键值对。
方法一:循环判断后添加
movie_cast = [{'id': 90633,'name': 'Gal Gadot','cast_id': 0, 'order': 0}, {'id': 62064, 'name': 'Chris Pine','cast_id': 15, 'order': 1}, {'id': 41091, 'name': 'Kristen Wiig', 'cast_id': 12,'order': 2}, {'id': 41092, 'name': 'Pedro Pascal', 'cast_id': 13, 'order': 3}, {'id': 32, 'name': 'Robin Wright', 'cast_id': 78, 'order': 4}] limit = 1 cast_limit = [] for item in movie_cast: # 根据目标结果,这里用<=而非< if item['order'] <= limit: cast_limit.append(item) print(cast_limit)
方法二:列表推导式(更简洁)
用Python列表推导式可以直接完成列表筛选,代码更紧凑:
movie_cast = [{'id': 90633,'name': 'Gal Gadot','cast_id': 0, 'order': 0}, {'id': 62064, 'name': 'Chris Pine','cast_id': 15, 'order': 1}, {'id': 41091, 'name': 'Kristen Wiig', 'cast_id': 12,'order': 2}, {'id': 41092, 'name': 'Pedro Pascal', 'cast_id': 13, 'order': 3}, {'id': 32, 'name': 'Robin Wright', 'cast_id': 78, 'order': 4}] limit = 1 cast_limit = [item for item in movie_cast if item['order'] <= limit] print(cast_limit)
两种方法都会输出你想要的desired_result,不会包含空字典。
内容的提问来源于stack exchange,提问作者user10018710
相关产品推荐
相关产品推荐

