简体   繁体   English

从字典列表中删除 null 个条目

[英]Removing null entries from a list of dictionaries

I have a list of dictionaries like this:我有一个这样的字典列表:

[
    {'property_a': 'a1', 'property_b': 'b1'},
    {'property_a': 'a2', 'property_b': 'b2'},
    {'property_a': 'a3'}
]

How can I remove the entries that do not have the property property_b ?如何删除不具有属性property_b的条目? I have tried accessing the property name somehow (example below):我试过以某种方式访问属性名称(下面的示例):

for entry in mylist['property_b']:
    for k in list(entry.keys()):
        if entry[k] == None:
            del entry[k]

But it doesn't work like that.但它不是那样工作的。

What I need is to remove those entries altogether, resulting in this list for example:我需要的是完全删除这些条目,例如生成此list

[
    {'property_a': 'a1', 'property_b': 'b1'},
    {'property_a': 'a2', 'property_b': 'b2'}
]

Try:尝试:

lst = [
    {"property_a": "a1", "property_b": "b1"},
    {"property_a": "a2", "property_b": "b2"},
    {"property_a": "a3"},
]

lst = [d for d in lst if "property_b" in d]
print(lst)

Prints:印刷:

[
    {"property_a": "a1", "property_b": "b1"},
    {"property_a": "a2", "property_b": "b2"},
]

mylist['property_b'] won't return anything as lists indices must always be integers (a list is just an array of items and 'property_b' is nested in those items so is not immediately accessible) mylist['property_b'] 不会返回任何内容,因为列表索引必须始终是整数(列表只是一个项目数组,'property_b' 嵌套在这些项目中,因此无法立即访问)

What you need to do is iterate through your list and check whether each dictionary contains 'property_b' as a key.您需要做的是遍历列表并检查每个字典是否包含“property_b”作为键。

This may be done either of the two following ways:这可以通过以下两种方式之一完成:

new_list = []

for item in mylist:
  if 'property_b' in item:
   new_list.append(item)

This would be my preferred way (using list comprehension):这将是我的首选方式(使用列表理解):

new_list = [item for item in mylist if 'property_b' in item]

They both do the same thing, the latter is just more elegant.他们都做同样的事情,后者更优雅。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM