Python:检查一个字典是否是另一个更大的字典的一个子集 [英] Python: Check if one dictionary is a subset of another larger dictionary

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

问题描述

我试图编写一个自定义过滤器方法,它接受任意数量的 kwargs ,并返回一个包含类似数据库列表的元素的列表,该列表包含那些 kwargs
$ b

例如,假设 d1 = {'a':'2','b':'3'} d2 =同样的事情。 d1 == d2 结果为True。但是,假设 d2 =相同的东西加上一堆其他东西。我的方法需要能够判断 d1是否在d2 中,但是Python不能用dictionaries来完成。



上下文:



我有一个Word类,每个对象的属性都像 word definition part_of_speech 等等。我希望能够在这些单词的主要列表上调用过滤器方法,如 Word.objects.filter(word ='jump',part_of_speech ='verb-implicit')。我无法弄清楚如何同时管理这些键和值。但是,这可能会有更大的功能以外的其他人的这种情况下。

解决方案

转换为项目对并检查包含。 >

  all(subset.items()中item的superset.items())



优化是读者的一个练习。


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.

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.

Context:

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.

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

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