美文网首页
python2 assert判断字典的包含关系

python2 assert判断字典的包含关系

作者: Elvis_zhou | 来源:发表于2019-12-02 18:06 被阅读0次

    python 2:

    在python2里,用assert判断一个字典是否是另一个字典的子集并不能直接用in, not in,只能用setissubset
    比较方法:

    a = {'x': 1, 'y': 2, 'z': 3}
    b = {'x': 1}
    c = {'y': 2, 'd': 3}
    
    assert six.viewitems(b) in six.viewitems(a)
    # 直接比较会出错
    """
    Traceback (most recent call last):
      File "/home/python/Desktop/zxc/others/six_test.py", line 21, in <module>
        assert six.viewitems(b) in six.viewitems(a)
    AssertionError
    """
    # 可以用:
    assert set(six.viewitems(b)).issubset(set(six.viewitems(a)))
    

    unittest的assert:

    a = {'x': 1, 'y': 2, 'z': 3}
    b = {'x': 1}
    c = {'y': 2, 'd': 3}
    
    
    class TestZ(unittest.TestCase):
    
        def test_compare(self):
    
            print six.viewitems(a)
            print six.viewitems(b)
            # self.assertTrue(set(six.viewitems(b)).issubset(six.viewitems(a)))
            self.assertFalse(set(six.viewitems(c)).issubset(six.viewitems(a)))
    
    
    if __name__ == '__main__':
        unittest.main()
    

    相关文章

      网友评论

          本文标题:python2 assert判断字典的包含关系

          本文链接:https://www.haomeiwen.com/subject/ntpfgctx.html