在Python中使用None值删除字典中键的正确方法 [英] Proper way to remove keys in dictionary with None values in Python

查看:393
本文介绍了在Python中使用None值删除字典中键的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中从值== None的字典中删除键的正确方法是什么?

What is the proper way to remove keys from a dictionary with value == None in Python?

推荐答案

通常,您将创建一个新的dict,它是通过过滤旧的dict构造的.字典理解对于这种事情很有用:

Generally, you'll create a new dict constructed from filtering the old one. dictionary comprehensions are great for this sort of thing:

{k: v for k, v in original.items() if v is not None}

如果您必须更新原始字典,则可以这样做...

If you must update the original dict, you can do it like this ...

filtered = {k: v for k, v in original.items() if v is not None}
original.clear()
original.update(filtered)

这可能是我可以想到的就地删除它们的最干净"的方式(在遍历字典时修改字典是不安全的)

This is probably the most "clean" way to remove them in-place that I can think of (it isn't safe to modify a dict while you're iterating over it)

在python2.x上使用original.iteritems()

这篇关于在Python中使用None值删除字典中键的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆