Python:在比较它们之前我需要对字典进行排序吗?

标签 python sorting dictionary data-structures

我希望将 JSON 响应的输出与我定义的字典进行比较。字典和 JSON 对象没有排序。

根据我自己的测试,此 JSON 响应存储为 res.data

{
    "message": "Staff name and password pair not match",
    "errors": {
        "resource": "Login",
        "field": "staff_authentication",
        "code": "invalid",
        "stack_trace": null
    }
}

我没有找到anything that refers to Dictionary comparison operator in Python documentation 。我读过有关对从 JSON 字符串加载的字典进行排序的文章,但根据我自己的测试,比较运算符无需排序即可正常工作。 与这个不同顺序的字典进行比较,将得到 True

invalid_password_json = dict(
                                    errors=dict(
                                        resource="Login",
                                        code="invalid",
                                        field="staff_authentication",
                                        stack_trace=None,),
                                        message="Staff name and password pair not match",
                                    )
        assert json.loads(res.data, object_pairs_hook=OrderedDict) == invalid_password_json

我需要使用 json.dumps(my_password, sort_keys=True)json.loads(res.data, object_pairs_hook=OrderedDict)) 来确保顺序比较之前?

最佳答案

据我所知,你不需要对字典的键进行排序,正如相当古老的 python documentation 中提到的那样。 :

Mappings (dictionaries) compare equal if and only if their sorted (key, value) lists compare equal.(5.4) Outcomes other than equality are resolved consistently, but are not otherwise defined. (5.5)

... equal. (5.4)

The implementation computes this efficiently, without constructing lists or sorting.

... defined. (5.5)

Earlier versions of Python used lexicographic comparison of the sorted (key, value) lists, but this was very expensive for the common case of comparing for equality. An even earlier version of Python compared dictionaries by identity only, but this caused surprises because people expected to be able to test a dictionary for emptiness by comparing it to {}.

此外,了解在 python 中字典是使用哈希表而不是平衡树实现的也很有帮助。

关于Python:在比较它们之前我需要对字典进行排序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46809337/

相关文章:

python - 使用 Matplotlib 为每行数据绘制多个条形图

sql - 多对多关系排序

使用归并排序对字符串进行排序

Java数据结构,一个以value里面的对象为key的map

python - 如何为目录中的每个文件添加随机数? (初学者)

python - 指纹疤痕/折痕产生器

python - 仅获取 ROI 中的像素,如何?

algorithm - 具有子节点的节点的排名算法?

json - Swift:将Optional<AnyObject> 转换为TimeInterval 错误

python - 生成python字典仅存储可迭代的最后一个值