如何用另一个字典过滤python字典?

2024-09-30 22:20:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个方法,该方法查看mainDict中的每个值,返回包含filterDict中列出的所有键值对的所有值的数组。在

def where(mainDicts, filterDict):
    pass

mydicts = [{'title': "title 1", 'author': "author 1", 'year': 1611},
           {'title': "title 2", 'author': "author 2", 'year': 1615},
           {'title': "title 3", 'author': "author 1", 'year': 1611}]

filterDict = {'year': 1611, 'author': "author 1"}

where(mydicts, filterDict)

我想还这个:

^{pr2}$

Tags: 方法titledefpass数组whereyearauthor
3条回答

只需使用列表理解,对于每个项d检查filterDict中的所有键k是否都在该项中,如果是,则值{}是否相同。在

def where(mainDict, filterDict):
    return [d for d in mainDict if all(k in d and d[k] == v 
                                       for k, v in filterDict.items())]

这也适用于python2。示例:

^{pr2}$

作为一种更python的方法,您可以使用^{}来获得字典和筛选器字典之间的交集,然后如果交集与filter相等,则可以返回它:

>>> filt={'author': 'author 1', 'year': 1611}
>>> [d for d in mydict if dict(filt.viewitems()&d.viewitems())==filt]
[{'author': 'author 1', 'year': 1611, 'title': 'title 1'}, {'author': 'author 1', 'year': 1611, 'title': 'title 3'}]

阅读有关字典视图对象的更多信息https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects

假设运行Python 3:

def where(mainDicts, filterDict):
    return [x for x in mainDicts if not filterDict.items() - x.items()]

引用文件:

Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like. For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^).

有关详细信息,请参阅Dictionary view objects。 如果您需要在python2中工作,只需将items()替换为^{}。在

示例:

^{pr2}$

请注意,如果您的值不可散列(请参见Glossary),则上面的方法将不起作用,但是下面的内容将

def where(dicts, filt):
    return [x for x in dicts if all(k in x and x[k] == v for k, v in filt.items())]

相关问题 更多 >