【发布时间】: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