假设我有两个Python字典-dictA
和dictB
。我需要找出是否有任何键存在于dictB
中,但不存在于dictA
中。最快的方法是什么?
我应该把字典的键转换成一组然后继续吗?
有兴趣知道你的想法。。。
谢谢你的回复。
很抱歉没有正确地陈述我的问题。
我的场景是这样的-我有一个dictA
,它可以与dictB
相同,或者可能与dictB
相比缺少一些键,或者某些键的值可能不同,必须设置为dictA
键的值。
问题是字典没有标准,可以有dict of dict的值
说
dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
因此'key2'值必须重置为新值,并且'key13'必须添加到dict中。 键值没有固定格式。它可以是一个简单的值或一个dict或一个dict的dict
可以对键使用设置操作:
这里有一个类来查找所有的可能性:添加了什么,删除了什么,哪些键值对是相同的,哪些键值对是更改的。
以下是一些示例输出:
作为github回购协议提供: https://github.com/hughdbrown/dictdiffer
如果您想递归地得到差异,我已经为python编写了一个包: https://github.com/seperman/deepdiff
安装
从PyPi安装:
示例用法
导入
同一对象返回空
项的类型已更改
项的值已更改
添加和/或删除的项目
字符串差异
字符串差异2
类型更改
列表差异
列表差异2:
忽略顺序或重复项列出差异:(使用与上面相同的词典)
包含词典的列表:
集合:
命名元组:
自定义对象:
添加的对象属性:
不确定它是否“快”,但通常情况下,人们可以这样做
相关问题 更多 >
编程相关推荐