python中字典相减_计算两个Python字典中包含的键的差异

Suppose I have two Python dictionaries - dictA and dictB. I need to find out if there are any keys which are present in dictB but not in dictA. What is the fastest way to go about it?

Should I convert the dictionary keys into a set and then go about?

Interested in knowing your thoughts...

Thanks for your responses.

Apologies for not stating my question properly.

My scenario is like this - I have a dictA which can be the same as dictB or may have some keys missing as compared to dictB or else the value of some keys might be different which has to be set to that of dictA key's value.

Problem is the dictionary has no standard and can have values which can be dict of dict.

Say

dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}

dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......

So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.

The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.

解决方案

You can use set operations on the keys:

diff = set(dictb.keys()) - set(dicta.keys())

Here is a class to find all the possibilities: what was added, what was removed, which key-value pairs are the same, and which key-value pairs are changed.

class DictDiffer(object):

"""

Calculate the difference between two dictionaries as:

(1) items added

(2) items removed

(3) keys same in both but changed values

(4) keys same in both and unchanged values

"""

def __init__(self, current_dict, past_dict):

self.current_dict, self.past_dict = current_dict, past_dict

self.set_current, self.set_past = set(current_dict.keys()), set(past_dict.keys())

self.intersect = self.set_current.intersection(self.set_past)

def added(self):

return self.set_current - self.intersect

def removed(self):

return self.set_past - self.intersect

def changed(self):

return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o])

def unchanged(self):

return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o])

Here is some sample output:

>>> a = {'a': 1, 'b': 1, 'c': 0}

>>> b = {'a': 1, 'b': 2, 'd': 0}

>>> d = DictDiffer(b, a)

>>> print "Added:", d.added()

Added: set(['d'])

>>> print "Removed:", d.removed()

Removed: set(['c'])

>>> print "Changed:", d.changed()

Changed: set(['b'])

>>> print "Unchanged:", d.unchanged()

Unchanged: set(['a'])

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值