如果特定键具有特殊值' none',我需要删除OrderedDict输出中的元素。 如果Data2和Data3都包含None作为条目,我需要删除元素。
# if both Data2 and Data3 is None
Key_to_check = [Data2,Data3]
Output=[OrderedDict([('index', 78), ('Name', u'Andy'), ('Data1', u'Taken'), ('Data2', u'Taken'),('Data3', u'Taken'),
OrderedDict([('index', 609), ('Name', u'Sam'), ('Data1', u'Taken'), ('Data2', None),('Data3', u'Taken'),
OrderedDict([('index', 680), ('Name', u'John'), ('Data1', u'Taken'), ('Data2', None),('Data3', None)]
由于John的数据2和数据3是None,因此它将被删除。如何获取输出以将其删除?
Output=[OrderedDict([('index', 78), ('Name', u'Andy'), ('Data1', u'Taken'), ('Data2', u'Taken'),('Data3', u'Taken'),
OrderedDict([('index', 609), ('Name', u'Sam'), ('Data1', u'Taken'), ('Data2', None),('Data3', u'Taken')]
答案 0 :(得分:2)
您可以使用此列表理解:
>>> from collections import OrderedDict
>>>
>>> Output=[OrderedDict([('index', 78), ('Name', u'Andy'), ('Data1', u'Taken'), ('Data2', u'Taken'),('Data3', u'Taken')]),OrderedDict([('index', 609), ('Name', u'Sam'), ('Data1', u'Taken'), ('Data2', None),('Data3', u'Taken')]),OrderedDict([('index', 680), ('Name', u'John'), ('Data1', u'Taken'), ('Data2', None),('Data3', None)])]
>>>
>>> [i for i in Output if i["Data2"] or i["Data3"]]
[OrderedDict([('index', 78), ('Name', u'Andy'), ('Data1', u'Taken'), ('Data2', u'Taken'), ('Data3', u'Taken')]), OrderedDict([('index', 609), ('Name', u'Sam'), ('Data1', u'Taken'), ('Data2', None), ('Data3', u'Taken')])
另一种方法,您可以使用内置函数any
,如下所示:
>>> [i for i in Output if any(i.get("Data{0}".format(j),None) for j in range(2,4))]
[OrderedDict([('index', 78), ('Name', u'Andy'), ('Data1', u'Taken'), ('Data2', u'Taken'), ('Data3', u'Taken')]), OrderedDict([('index', 609), ('Name', u'Sam'), ('Data1', u'Taken'), ('Data2', None), ('Data3', u'Taken')])]
如果您有Data2,Data3 ...数据100,请将range(2,4)
更改为range(2,101)
。
如果iterable的任何元素为true,则返回True。如果是可迭代的 空,返回False。
答案 1 :(得分:0)
让我们试试:
temp= {k:v for k,v in Data2.items() if (v is not None) or (Data3.get(k, 'Not Existed') is not None)}
Data3 = {k:v for k,v in Data3.items() if (v is not None) or (Data2.get(k, 'Not Existed') is not None)}
Data2 = temp
或更短的版本:
Data2, Data3 = {k:v for k,v in Data2.items() if (v is not None) or (Data3.get(k, 'Not Existed') is not None)}, {k:v for k,v in Data3.items() if (v is not None) or (Data2.get(k, 'Not Existed') is not None)}