对于像x = {'a': 1, 'b': 2}
这样的单层dict,问题很容易解决,所以(Pythonic way to check if two dictionaries have the identical set of keys?)但是嵌套dict呢?
例如,y = {'a': {'c': 3}, 'b': {'d': 4}}
有键'a'
和'b'
,但我想将其形状与另一个嵌套的dict结构(如z = {'a': {'c': 5}, 'b': {'d': 6}}
)进行比较,后者具有与y
相同的形状和键(不同的值很好)。w = {'a': {'c': 3}, 'b': {'e': 4}}
有键'a'
和'b'
,但在下一层上它与y
不同,因为w['b']
有键'e'
,而y['b']
有键'd'
。
想要一个由两个参数dict_1
和dict_2
组成的短/简单函数,如果它们具有上述相同的形状和键,则返回True
,否则返回False
。
要分析当前存在的两个答案,首先让导入
timeit
:现在我们需要设置代码:
现在让我们测试一下这两个选项,首先使用Python3.3!
看起来我的解决方案花费了2/3到3/4的时间,使其速度超过1.25倍。
在我自己编译的Python 3.4(alpha)版本上:
还是差不多的比例。两者之间的时间差很可能是因为我在没有优化的情况下自行编译了3.4。
感谢所有读者!
我喜欢nneonneo的答案,而且应该比较快,但我希望不创建额外的不必要的数据结构(我一直在学习Python中的内存碎片)。这可能快,也可能不快。
(编辑:剧透!)
但是,如果要处理很多这样的问题,并且有内存问题,那么最好这样做。
实施
这在Python 3中应该有效,如果将
keys
转换为viewkeys
,可能是2.7,当然不是2.6。它依赖于dict拥有的键的集合视图:编辑更新以减少冗余类型检查,现在更有效。
测试
检查:
印刷品:
这将提供两个词典的副本,其中不包含任何非词典值,然后对它们进行比较:
相关问题 更多 >
编程相关推荐