python - 检查 Python 字典是否具有相同的形状和键

标签 python dictionary

对于像 x = {'a': 1, 'b': 2} 这样的单层字典,问题很简单并且可以在 SO ( Pythonic way to check if two dictionaries have the identical set of keys? ) 上找到答案,但是嵌套字典呢?

例如,y = {'a': {'c': 3}, 'b': {'d': 4}} 有键 'a''b' 但我想将它的形状与另一个嵌套的字典结构进行比较,例如 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_1dict_2 的简短函数,如果它们具有与上述相同的形状和键,则返回 True,否则为 False

最佳答案

这提供了两个字典的副本,去除了任何非字典值,然后比较它们:

def getshape(d):
    if isinstance(d, dict):
        return {k:getshape(d[k]) for k in d}
    else:
        # Replace all non-dict values with None.
        return None

def shape_equal(d1, d2):
    return getshape(d1) == getshape(d2)

关于python - 检查 Python 字典是否具有相同的形状和键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24192748/

相关文章:

python - 在 Python 中使用 OpenCV 检测掌纹

python - 如何检查字典是否在python中的另一个字典中

java - 覆盖哈希码方法时的HashMap性能

python - 使用范围作为字典中的键

python - 动态改变 __slots__

python - Keras ModelCheckpoint 在保存模型的同时引入了额外的层

python - 从 Pandas 数据帧转换为 HTML 时,如何在 HTML 中显示完整(未截断)的数据帧信息?

python - 多次遍历文件(Python)

python - 使用 FFMPEG 命令读取帧并使用 opencv 中的 inshow 函数显示

python - 使用 lxml 将 XML 转换为 Python 中的字典