如何检查一本字典是否是另一本更大字典的子集? [英] How to check if one dictionary is a subset of another larger dictionary?

查看:46
本文介绍了如何检查一本字典是否是另一本更大字典的子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个自定义过滤器方法,该方法接受任意数量的 kwargs 并返回一个列表,该列表包含包含这些 kwargs.

I'm trying to write a custom filter method that takes an arbitrary number of kwargs and returns a list containing the elements of a database-like list that contain those kwargs.

例如,假设 d1 = {'a':'2', 'b':'3'}d2 = 相同.d1 == d2 结果为真.但是假设 d2 = 相同的东西加上一堆其他的东西.我的方法需要能够判断 d1 in d2,但 Python 不能用字典做到这一点.

For example, suppose d1 = {'a':'2', 'b':'3'} and d2 = the same thing. d1 == d2 results in True. But suppose d2 = the same thing plus a bunch of other things. My method needs to be able to tell if d1 in d2, but Python can't do that with dictionaries.

上下文:

我有一个 Word 类,每个对象都有诸如 worddefinitionpart_of_speech 等属性.我希望能够对这些单词的主列表调用过滤器方法,例如 Word.objects.filter(word='jump', part_of_speech='verb-intransitive').我不知道如何同时管理这些键和值.但是对于其他人来说,这可能会在此上下文之外具有更大的功能.

I have a Word class, and each object has properties like word, definition, part_of_speech, and so on. I want to be able to call a filter method on the main list of these words, like Word.objects.filter(word='jump', part_of_speech='verb-intransitive'). I can't figure out how to manage these keys and values at the same time. But this could have larger functionality outside this context for other people.

推荐答案

转换为项目对并检查是否包含.

Convert to item pairs and check for containment.

all(item in superset.items() for item in subset.items())

优化留给读者作为练习.

Optimization is left as an exercise for the reader.

这篇关于如何检查一本字典是否是另一本更大字典的子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆