从字典中删除混合数据类型的空对象和空对象 [英] Removing nulls and empty objects of mixed data types from a dictionary
本文介绍了从字典中删除混合数据类型的空对象和空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何清理包含多种数据类型的null和空列表,字典等字典,例如
How would one go about cleaning a dictionary containing a variety of datatypes of nulls and empty lists, dicts etc. E.g.
raw = {'key': 'value', 'key1': [], 'key2': {}, 'key3': True, 'key4': None}
收件人:
refined = {'key': 'value', 'key3': true}
由于字典中数据类型的混合性质,因此使用:
Because of the mixed nature of data types in the dictionary, using:
refined = {k:v for k,v in processed.items() if len(v)>0}
抛出
TypeError:类型为'bool'的对象没有len()
TypeError: object of type 'bool' has no len()
是否有一种基于type(v) is bool
的第二个条件的解决方案?
Is there a solution to make a second conditional based on type(v) is bool
?
我发现我在使用解决方案时遇到的问题是数据结构的结果,并提出了一个单独的问题来解决这个问题.
I've found the issue I was encountering employing solutions was a result of the structure of the data, asking a separate question to deal with that.
推荐答案
您可以尝试一下.
refined={k:v for k,v in raw.items() if v or isinstance(v,bool)}
raw={'key': 'value',
'key1': [],
'key2': {},
'key3': True,
'key4': None,
'key5': False}
refined={k:v for k,v in raw.items() if v or isinstance(v,bool)}
#{'key': 'value', 'key3': True, 'key5': False}
这篇关于从字典中删除混合数据类型的空对象和空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文