python判断两个字典是否相等_关于python:断言两个字典几乎相等

更新时间:2023-07-14 13:26:44 阅读: 评论:0

python判断两个字典是否相等_关于python:断⾔两个字典⼏
乎相等
我试图断⾔两个字典⼏乎相等,但是我似乎做不到。
这是⼀个例⼦:
保育员培训
>>> ls as nt
>>> nt.asrt_dict_equal({'a' : 12.4}, {'a' : 5.6 + 6.8})
Traceback (most recent call last):
File"", line 1, in
File"/usr/lib/python2.7/unittest/ca.py", line 838, in asrtDictEqual
lf.fail(lf._formatMessage(msg, standardMsg))
File"/usr/lib/python2.7/unittest/ca.py", line 413, in fail
rai lf.failureException(msg)
AsrtionError: {'a': 12.4} != {'a': 12.399999999999999}
- {'a': 12.4}中小学辅导
+ {'a': 12.399999999999999}
我希望这样通过:
>>> nt.asrt_almost_equal(12.4, 5.6 + 6.8)
我希望我缺少诸如nt.asrt_almost_dict_equal之类的简单内容,或者可能有⼀个参数可以传递给nt.asrt_dict_equal,该参数指定浮点应该接近的程度,但是我什么也找不到。
当然,我可以遍历字典并使⽤nt.asrt_almost_equal分别⽐较值; 但是,就我⽽⾔,字典更为复杂,因此我希望避免这种情况。
断⾔两个词典⼏乎相等的最佳⽅法是什么?
我认为您需要⾃⼰迭代并⽐较这些值。 asrt_almost_equal仅提供可直接计算其差的数字类型。
如果您发现需要⾃⼰动⼿,请在此处查看" asrtDeepAlmostEqual":/larsbutler/oq-engine/blob/master/tests/utils/
@dano,很有趣。
@dano的评论回答了我的问题:
我从dano提供的链接中复制了⼀个函数
import unittest
import numpy
def asrtDeepAlmostEqual(test_ca, expected, actual, *args, **kwargs):
"""
Asrt that two complex structures have almost equal contents.
Compares lists, dicts and tuples recursively. Checks numeric values
using test_ca's :py:meth:`unittest.TestCa.asrtAlmostEqual` and
checks all other values with :py:meth:`unittest.TestCa.asrtEqual`.
Accepts additional positional and keyword arguments and pass tho intact to asrtAlmostEqual() (that's how you specify comparison precision).cloudcomputing
:param test_ca: TestCa object on which we can call all of the basic 'asrt' methods.
:type test_ca: :py:class:`unittest.TestCa` object
"""
is_root = not '__trace' in kwargs
trace = kwargs.pop('__trace', 'ROOT')
try:
if isinstance(expected, (int, float, long, complex)):
test_ca.asrtAlmostEqual(expected, actual, *args, **kwargs)
elif isinstance(expected, (list, tuple, numpy.ndarray)):
test_ca.asrtEqual(len(expected), len(actual))
for index in xrange(len(expected)):
v1, v2 = expected[index], actual[index]
asrtDeepAlmostEqual(test_ca, v1, v2,
__trace=repr(index), *args, **kwargs)
elif isinstance(expected, dict):
sanwatest_ca.asrtEqual(t(expected), t(actual))
for key in expected:
asrtDeepAlmostEqual(test_ca, expected[key], actual[key],
__trace=repr(key), *args, **kwargs)
el:
test_ca.asrtEqual(expected, actual)
forgivemeexcept AsrtionError as exc:
exc.__dict__.tdefault('traces', []).append(trace)
if is_root:
trace = ' -> '.join(aces))
exc = AsrtionError("%s
TRACE: %s" % (ssage, trace))
rai exc
# My part, using the function
class TestMyClass(unittest.TestCa):
def test_dicts(lf):
asrtDeepAlmostEqual(lf, {'a' : 12.4}, {'a' : 5.6 + 6.8})
def test_dicts_2(lf):
dict_1 = {'a' : {'b' : [12.4, 0.3]}}
dict_2 = {'a' : {'b' : [5.6 + 6.8, 0.1 + 0.2]}}
asrtDeepAlmostEqual(lf, dict_1, dict_2)
cpichdef main():
unittest.main()
if __name__ =="__main__":
main()
结果:
Ran 2 tests in 0.000s
OK
拒绝投票,您能解释⼀下拒绝投票的原因。 我相信⾃我解答很好。 您认为我对@dano的贡献不⾜吗?
它的风格可能很差,但是如果您通过unittest.TestCa.asrtDeepAlmostEqual = asrtDeepAlmostEqual`来修补TestCa,则可以像其他任何⽅法⼀样使⽤测试,例如 lf.asrtDeepAlmostEqual(dict_1, dict_2)
还应该注意,在我的情况下,我必须对所有嵌套集合进⾏排序,因此您可以将此处的代码与此代码段⼀起使⽤,以对嵌套集合进⾏排序
@patricksurry可能将其转换为mixin的情况
荨麻属⽆需猴⼦修补TestCa。 您可以简单地将其⼦类化。 确实,这就是testtools.TestCa的作⽤。
我知道您不会只是为了执⾏此操作⽽导⼊熊猫,但是如果您碰巧正在使⽤熊猫,则可以将字典转换为序列并使⽤sting中的asrt_ries_equal,默认情况下,该asrt_ries_equal具有check_exact=Fal。
>>> import pandas as pd
>>> sting import asrt_ries_equal
>>> a = pd.Series({'a' : 12.4})
>>> b = pd.Series({'a': 12.399999999999999})
>>> asrt_ries_equal(a, b)董事长英文翻译
我⽆法运⾏Akavall的函数,所以我⾃⼰做了。 有点太简单了,但是可以满⾜我的⽬的。 使⽤pytest编写的⽤于测试该功能正常⼯作的代码
from numbers import Number
from math import isclo
def dictsAlmostEqual(dict1, dict2, rel_tol=1e-8):
"""
If dictionary value is a number, then check that the numbers are almost equal, otherwi check if values are exactly equal
Note: does not currently try converting strings to digits and comparing them. Does not care about ordering of keys in dictionaries
Just returns true or fal
"""
if len(dict1) != len(dict2):
return Fal
prosperous的名词# Loop through each item in the first dict and compare it to the cond dict
for key, item in dict1.items():
# If it is a nested dictionary, need to call the function again
if isinstance(item, dict):
# If the nested dictionaries are not almost equal, return Fal
communistparty
if not dictsAlmostEqual(dict1[key], dict2[key], rel_tol=rel_tol):
return Fal
# If it's not a dictionary, then continue comparing
# Put in el statement or el the nested dictionary will get compared twice and # On the cond time will check for exactly equal and will fail
el:
# If the value is a number, check if they are approximately equal
if isinstance(item, Number):
# if not abs(dict1[key] - dict2[key]) <= rel_tol:
if not isclo(dict1[key], dict2[key], rel_tol=rel_tol):
return Fal
el:
if not (dict1[key] == dict2[key]):
return Fal
return True
使⽤pytest验证函数输出
import pytest
import dictsAlmostEqual
def test_dictsAlmostEqual():
a = {}
b = {}
asrt dictsAlmostEqual(a, b)
a = {"1":"a"}
b = {}
asrt not dictsAlmostEqual(a, b)
a = {"1":"a"}
b = {"1":"a"}
asrt dictsAlmostEqual(a, b)
a = {"1":"a"}
b = {"1":"b"}
asrt not dictsAlmostEqual(a, b)
a = {"1":"1.23"}
b = {"1":"1.23"}
asrt dictsAlmostEqual(a, b)
a = {"1":"1.234"}
b = {"1":"1.23"}
asrt not dictsAlmostEqual(a, b)
a = {"1": 1.000000000000001,"2":"a"}
b = {"1": 1.000000000000002,"2":"a"}
asrt not dictsAlmostEqual(a, b, rel_tol=1e-20)
asrt dictsAlmostEqual(a, b, rel_tol=1e-8)
asrt dictsAlmostEqual(a, b)
# Nested dicts
a = {"1": {"2": 1.000000000000001}}
b = {"1": {"2": 1.000000000000002}}
asrt not dictsAlmostEqual(a, b, rel_tol=1e-20)
asrt dictsAlmostEqual(a, b, rel_tol=1e-8)
asrt dictsAlmostEqual(a, b)
a = {"1": {"2": 1.000000000000001,"3":"a"},"2":"1.23"}
b = {"1": {"2": 1.000000000000002,"3":"a"},"2":"1.23"} asrt not dictsAlmostEqual(a, b, rel_tol=1e-20)
asrt dictsAlmostEqual(a, b, rel_tol=1e-8)
asrt dictsAlmostEqual(a, b)

本文发布于:2023-07-14 13:26:44,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/90/177185.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:字典   测试   需要   参数   相等
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图