Python如何从for循环中的字典列表中删除空行?

标签 python dictionary

我有一个名为“行”的字典列表。但是,此列表包含一些具有空值(标记为“无”)的字典。如果在名为“lat”的键中找到“None”,我该如何编写遍历每一行并删除整行的 for 循环?

这是我的字典列表(“行”)。我想编写一个删除第一行的 for 循环,因为“lat”值为“None”。任何帮助将不胜感激!

[{'created_at': None, 'userid': None, 'long': None, 'tweetid': None, 'timestamp': None, 'lat': None},
 {'created_at': 'Mon May 04 04:35:34 +0000 2015', 'userid': '113503286', 'long': '-87.624387', 'tweetid': '595084326489956352', 'timestamp': '1430714134224', 'lat': '41.852653'}, 
 {'created_at': 'Mon May 04 04:35:46 +0000 2015', 'userid': '2421024865', 'long': '-87.629798', 'tweetid': '595084376632729600', 'timestamp': '1430714146179', 'lat': '41.878114'}]

最佳答案

List Comprehensions 是必经之路。

rows = [{'created_at': None, 'userid': None, 'long': None, 'tweetid': None, 'timestamp': None, 'lat': None},
 {'created_at': 'Mon May 04 04:35:34 +0000 2015', 'userid': '113503286', 'long': '-87.624387', 'tweetid': '595084326489956352', 'timestamp': '1430714134224', 'lat': '41.852653'}, 
 {'created_at': 'Mon May 04 04:35:46 +0000 2015', 'userid': '2421024865', 'long': '-87.629798', 'tweetid': '595084376632729600', 'timestamp': '1430714146179', 'lat': '41.878114'}]
rows = [ row for row in rows if row['lat'] is not None ]

你可以阅读 list comprehensions documentation了解更多。

关于Python如何从for循环中的字典列表中删除空行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30034501/

相关文章:

python - 如何在 pandas df 中逐个单元地操作数据?

python - 使用 tf.range 附加到循环中的列表

python - 欧拉计划 #45 : How is my logic wrong?

c# - MVC3 模型绑定(bind)器无法绑定(bind)属于我的 ViewModel 一部分的 Dictionary<string, bool>

ios - Swift 字典 UIPickerView (键)和 UITableView (值)

c# - Hashtable、Dictionary 和 KeyValuePair 有什么区别?

php - 将嵌套的 PHP 数组转换为嵌套的 Python 字典

python - 在Python中,当调用 __iter__ 时,将 "reset"用作迭代器是一个不好的做法吗?

python - 将值是不同长度列表的字典转换为数据框

python - Numpy 向量化相对距离