比较包含unicode和字节字符串的字典

时间:2019-01-08 19:13:14

标签: python python-2.7 dictionary

我正在尝试比较两个字典是否相等。字典具有嵌套的字典结构。通过阅读文档,我了解Python应该能够比较它们。唯一的区别是一个拥有字符串,另一个拥有unicode字符串(我在Python 2上)。

> state in states
False
> dict(state) == dict(states[0])
False
> json.dumps(state, sort_keys=True) == json.dumps(states[0], sort_keys=True)
True

唯一的区别是顶级字典和嵌套字典的键一个是字符串,另一个是unicode,但是测试玩具示例似乎并不在意。

> state.keys() == states[0].keys()
True
> state.keys()
['slots', 'responses']
> states[0].keys()
[u'slots', u'responses']
> {'a':1, 'b': {'c':2}} == {u'a':1, u'b': {u'c':2}}
True

我已经将这些词典包装在一个类中,并且可以使用JSON执行操作,但是我想了解发生了什么。

class OverloadedDict(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)
        self.__dict__ = self

    def __hash__(self):
        return hash(json.dumps(dict(self), sort_keys=True))

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return json.dumps(dict(self), sort_keys=True) == json.dumps(dict(other), sort_keys=True)
        else:
            return False

    def __ne__(self, other):
        return not (self == other)

我想避免不得不将它们转换为JSON。 是否有一种简单有效的方法来比较它们的平等性和成员资格?

更新

注释中的

@ juanpa.arrivillaga建议通过使用from __future__ import unicode_literals切换到Unicode文字。这是行不通的,因为字典是用关键字参数初始化的。 导入unicode_literals后,dict({'a':1})将是{u'a': 1},但dict(a=1)仍将是{'a': 1}

0 个答案:

没有答案