簡體   English   中英

Python 2.7:如果鍵缺失或為空,則刪除列表中的字典

[英]Python 2.7: Removing a dict in a list if a key is missing or empty

有問題的列表看起來像這樣,只有適用於任何帖子的博客列表:

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中進行處理。

編輯添加了確切的錯誤信息。

首先,所有數據結構不是有效的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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM