【问题标题】:Python 2.7: Removing a dict in a list if a key is missing or emptyPython 2.7:如果键丢失或为空,则删除列表中的字典
【发布时间】:2017-08-17 05:00:33
【问题描述】:

有问题的列表看起来像这样,只是一个包含任何帖子的博客列表(如果适用):

blogs = {
            {
             'id': 1, 
             'title': 'Foodies', 
             'posts': {
                  { 'id': 28, 'title': 'Sourdough Bread starter', 'blog_id': 1},
                  { 'id': 64, 'title': 'How to make brioche in under 4 hours', 'blog_id': 1}
                 }
            },{
                'id': 2, 
                'title': 'Southern Meals', 
                'posts': {}
            },{
               'id': 3, 
               'title': 'Vegomamma'
            },{
               'id': 4, 
               'title': 'Culinare'
            }
        }

我只想要带有帖子的博客,因此我正在尝试减少列表,以便只返回第一个字典。

这是我尝试过的,但引发了错误: "'dict' 对象没有属性 'posts'"

我明白,但我正在尝试删除没有该属性的字典。

for b in blogs:
    if "posts" not in b or b.posts.count() == 0:
        blogs.remove(b)

为什么会失败?这似乎是一个非常简单的解决方案,我以前使用过它。

这个应用程序是用 Python 和 Angular 构建的,所以我可以在 Angular 中进行过滤,但我宁愿在 Python 中处理它。

编辑添加了确切的错误消息。

【问题讨论】:

  • 请告诉我们它抛出的错误,以便更容易查明问题。
  • TypeError: unhashable type: 'dict'
  • 这是b['posts'].count() .....
  • 可能最外部的 { } 应该是 [ ] 以创建实际列表
  • 谢谢,这就是我的本意。

标签: python python-2.7 dictionary filtering


【解决方案1】:

首先,您的所有数据结构都不是有效的 python 对象。您有一组包含不是可散列对象的字典(将引发TypeError)。根据您的问题主体,它似乎是一个列表。其次,您不需要检查字典中是否存在posts,您可以在列表理解中使用dict.get()get 方法如果缺少密钥则返回 None:

In [20]: [b for b in blogs if b.get('posts')]
Out[20]: 
[{'posts': [{'id': 28, 'title': 'Sourdough Bread starter', 'blog_id': 1},
   {'id': 64, 'title': 'How to make brioche in under 4 hours', 'blog_id': 1}],
  'id': 1,
  'title': 'Foodies'}]

另外,请注意,由于 post 应该是可迭代的,因此如果它为空(它评估为 False),验证检查将失败。这就是为什么我只使用if b.get('posts')

【讨论】:

  • 谢谢!这比我要工作的答案优雅得多。
猜你喜欢
  • 2021-12-28
  • 1970-01-01
  • 2020-11-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多