【问题标题】:Loop through dict key equals to list than put in new list遍历dict键等于列表而不是放入新列表
【发布时间】:2017-04-07 15:50:29
【问题描述】:

我现在有一个相当大的字典,它是这样设置的:

largedict = {'journalname':{code: 2065},'journalname1':{code: 3055}}

等等等等。还有一本字典:

codes = {3055: 'medicine',3786: 'sciences'}

我想遍历 largedict,将它的代码值与代码中的键进行比较。然后要么将所有与代码匹配的 journalname 键/值对添加到不同的字典中,要么从 largedict 中删除所有不匹配的键/值对。

【问题讨论】:

    标签: python-2.7 loops dictionary


    【解决方案1】:
    new_dic = {journal_name : journal_body for journal_name, journal_body in largedict.items() if journal_body["code"] in codes}
    

    【讨论】:

    • 或 python 2.7 中的 iteritems()
    • 这让我回过神来:TypeError: list indices must be integers, not str
    猜你喜欢
    • 2013-06-02
    • 1970-01-01
    • 2015-02-12
    • 2016-09-23
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多