Skip to content Skip to sidebar Skip to footer

Python Multiple Dict Compare

I have one dict and want to compare with 3 more dict. If key does not exist in any of the 3 dict, then to create a new dict with that key, value pair, Also, skip if the key and va

Solution 1:

Here's a solution for Python 3.3. This also works in Python 2.7, but there I would use .iteritems() instead of .items():

>>>a = {"a":1, "b":2, "c":3, "d":4}>>>b = {"a":10, "b":20}>>>c = {"p":100, "q":200, "c":300}>>>d = {"a":1000, "x":2000, "c":3}>>>p_dict = {k:v for k,v in a.items() ...ifnotany(k in dicts for dicts in (b,c,d))}>>>p_dict
{'d': 4}
>>>q_dict = {k:v for k,v in a.items()...ifany(k in dicts for dicts in (b,c,d))...andnotany(dicts.get(k)==v for dicts in (b,c,d))}>>>q_dict
{'a': 1, 'b': 2}

This assumes that none of the values in your dicts are None.

Solution 2:

Here's a 2.x (not using dict comprehension) solution based on Tim Pietzcer's approach:

In [680]: dicts=[b,c,d]

In [681]: p_dict=dict([(k,v) for k,v in a.iteritems()
                      ifnotany(k in di for di in dicts)])

In [682]: p_dict
Out[682]: {'d': '4'}

In [683]: q_dict=dict([(k,v) for k,v in a.iteritems() 
                      ifany(k in di for di in dicts)
                      andnotany(di.get(k)==v for di in dicts) ])

In [684]: q_dict
Out[684]: {'a': '1', 'b': '2'}

Post a Comment for "Python Multiple Dict Compare"