python - 如何在 Python 中过滤字典?

标签 python dictionary

d = {'foo': 'x',
     'bar': 'y',
     'zoo': 'None',
     'foobar': 'None'}

我想过滤所有值为 'None' 的项目,并用特定值更新 foobar 项目。我试过:

for i in x.items():
   ....:    if i[i] == 'None':
   ....:        x.pop(i[0])
   ....:    else:
   ....:        x.update({i[0]:'updated'}) 

但它不起作用。

最佳答案

不清楚您发布的字典中的'None' 是什么。如果是字符串,可以使用如下:

dict((k, 'updated') for k, v in d.items() if v != 'None')

如果是None,就替换检查,例如:

dict((k, 'updated') for k, v in d.items() if v is None)

(如果您仍在使用 Python 2,请将 .items() 替换为 .iteritems())

关于python - 如何在 Python 中过滤字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4484690/

相关文章:

Python-MySQL : How to insert multiple data into MySQL database?

python - 跨多个键对嵌套字典进行排序

ios - 打开一个警报,要求选择应用程序打开 map

Python SQL 对象按字典和日期选择数据

c# - 我编写的函数中出现奇怪的空引用异常

python - 如何在不重新安装模块的情况下更新 mac python

python - 使用 `scipy.sparse` 构建一个简单的线性系统

python - 无法将一行移动到数据框的顶部

Python,导入模块进行测试

python - 使用字典在模型中创建对象时出现 Django TypeError