我想创建一个方法,该方法查看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}$
只需使用列表理解,对于每个项}是否相同。在
d
检查filterDict
中的所有键k
是否都在该项中,如果是,则值{这也适用于python2。示例:
^{pr2}$作为一种更python的方法,您可以使用^{} 来获得字典和筛选器字典之间的交集,然后如果交集与filter相等,则可以返回它:
阅读有关字典视图对象的更多信息https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects
假设运行Python 3:
引用文件:
有关详细信息,请参阅Dictionary view objects。 如果您需要在python2中工作,只需将} 。在
items()
替换为^{示例:
^{pr2}$请注意,如果您的值不可散列(请参见Glossary),则上面的方法将不起作用,但是下面的内容将
相关问题 更多 >
编程相关推荐