从非元值的{t 44}创建dict

时间:2016-02-14 14:47:59

标签: python

我在下面给出的代码中有tupleNone值(在ref中打印)。我正在使用主代码中其他位置定义的dictionaryref创建self.entries

def parsing_write(self, filename):
    # print(self.booklist)
    datalist = []
    writer = BibTexWriter()
    writer.indent = '    '
    for ref in self.booklist:
        print(type(ref))
        print(ref)
        datadict = dict(zip(self.entries, ref))
        datalist.append(datadict)
        print(type(datadict))
        print(type(datalist))
        print(datalist)

代码的结果,如下所示,显然包含具有None值的键,为(函数的完整输出):

<class 'tuple'>
('article', 'ebert2011', '\\textit{Ab Initio} Calculation of the Gilbert Damping Parameter via the Linear Response Formalism', 'Ebert, H. and Mankovsky, S. and K{\\"o}dderitzsch, D. and Kelly, P. J.', 'Phys. Rev. Lett.', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None)
<class 'dict'>
<class 'list'>
[{'Number': None, 'Booktitle': None, 'Crossred': None, 'author': 'Ebert, H. and Mankovsky, S. and K{\\"o}dderitzsch, D. and Kelly, P. J.', 'Series': None, 'Publishers': None, 'Organization': None, 'Address': None, 'Chapter': None, 'Note': None, 'Publisher': None, 'Annote': None, 'Month': None, 'Type': None, 'Institution': None, 'Edition': None, 'year': None, 'title': '\\textit{Ab Initio} Calculation of the Gilbert Damping Parameter via the Linear Response Formalism', 'ENTRYTYPE': 'article', 'Editor': None, 'journal': 'Phys. Rev. Lett.', 'ID': 'ebert2011', 'Page': None, 'HowPublished': None, 'Pages': None, 'School': None}]

但我希望dict只包含非None值的键和值。 我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

使用生成器理解来过滤掉None

的值
datadict = dict((k, v) for k, v in zip(self.entries, ref) if v is not None)

你也可以在2.7 +中使用dict理解:

datadict = {k: v for k, v in zip(self.entries, ref) if v is not None}

答案 1 :(得分:2)

使用dict理解来过滤这些值:

datadict = {k: v for k, v in zip(self.entries, ref) if v is not None}

有关理解如何运作的更多信息,请参阅Python tutorial