Python中文
首页
教程
问答
标签
搜索
登录
注册
测试di中是否包含dict
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>对于python dicts来说,平等性测试的工作原理如下:</p> <pre><code>first = {"one":"un", "two":"deux", "three":"trois"} second = {"one":"un", "two":"deux", "three":"trois"} print(first == second) # Result: True </code></pre> <p>但现在我的第二个dict包含了一些我想忽略的额外键:</p> <pre><code>first = {"one":"un", "two":"deux", "three":"trois"} second = {"one":"un", "two":"deux", "three":"trois", "foo":"bar"} </code></pre> <p><strong>有没有一种简单的方法来测试第一个dict是否是第二个dict的一部分,以及它的所有键和值?</strong></p> <p><strong>编辑1:</strong></p> <p>这个问题被怀疑是<a href="https://stackoverflow.com/questions/3415347/how-to-test-if-a-dictionary-contains-certain-keys">How to test if a dictionary contains certain <em>keys</em></a>的重复,但我对测试键<em>及其值</em>感兴趣。仅仅包含相同的键并不能使两个dict相等。</p> <p><strong>编辑2:</strong></p> <p>好吧,我现在用四种不同的方法得到了一些答案,并证明了它们都是有效的。由于我需要一个快速的过程,我测试了每个进程的执行时间。我用1000个条目创建了三个相同的dict,键和值是长度为10的随机字符串。<code>second</code>和<code>third</code>得到了一些额外的键值对,而<code>third</code>的最后一个非额外的键得到了一个新的值。因此,<code>first</code>是<code>second</code>的子集,而不是<code>third</code>的子集。使用模块<code>timeit</code>,重复10000次,我得到:</p> <pre><code>Method Time [s] first.viewitems() <=second.viewitems() 0.9 set(first.items()).issubset(second.items()) 7.3 len(set(first.items()) & set(second.items())) == len(first) 8.5 all(first[key] == second.get(key, sentinel) for key in first) 6.0 </code></pre> <p>我猜最后一种方法是最慢的,但在第二个地方。 但方法一胜过一切。</p> <p>谢谢你的回答!</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<pre><code>all(k in second and second[k] == v for k, v in first.items()) </code></pre> <p>如果您知道这些值都不能是<code>None</code>,那么它将简化为:</p> <pre><code>all(second.get(k, None) == v for k, v in first.items()) </code></pre>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
Python中两个字典的交集
6 回答
python中两个字符串上的异或操作数?
10 回答
Python中两个字符串中的类似句子
6 回答
Python中两个字符串之间的Hamming距离
9 回答
python中两个字符串之间的匹配模式
1 回答
python中两个字符串之间的按位或
7 回答
python中两个字符串之间的数据(字节)切片
10 回答
python中两个字符串之间的模式
3 回答
python中两个字符串作为子字符串的区别
8 回答
Python中两个字符串元组的比较
5 回答
Python中两个字符串列表中的公共字符串
3 回答
python中两个字符串的Anagram测试
1 回答
Python中两个字符串的正则匹配
3 回答
python中两个字符串的笛卡尔乘积
9 回答
Python中两个字符串相似性的比较
8 回答
python中两个字符串语义相似度的求法
2 回答
Python中两个字符置换成固定长度的字符串,每个字符的数目相等
10 回答
Python中两个对数方程之间的插值和平滑数据
4 回答
Python中两个对象之间的And/Or运算符
3 回答
python中两个嵌套字典中相似键的和值
8 回答