您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

两个python字典(键和值)的递归差异

两个python字典(键和值)的递归差异

一种选择是将您遇到的所有列表转换成字典,并将索引作为键。例如:

# add this function to the same module
def list_to_dict(l):
    return dict(zip(map(str, range(len(l))), l))



# add this code under the 'if type(d2[k]) == dict' block
                    elif type(d2[k]) == list:
                        dd(list_to_dict(d1[k]), list_to_dict(d2[k]), k)

这是带有注释的示例词典的输出

>>> d1 = {"name":"Joe", "Pets":[{"name":"spot", "species":"dog"}]}
>>> d2 = {"name":"Joe", "Pets":[{"name":"spot", "species":"cat"}]}
>>> dd(d1, d2, "base")
Changes in base
Changes in Pets
Changes in 0
species changed in d2 to cat
Done with changes in 0
Done with changes in Pets
Done with changes in base

请注意,这将按索引对索引进行比较,因此需要进行一些修改才能很好地适用于添加删除的列表项。

python 2022/1/1 18:35:28 有230人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶