Search code examples
pythonmergerow

combining dictionaries to keep same values along with different values


I have two dictionaries with the values.

x = {'a': 1, 'b': 2, 'c': 3, 'd':2}
y = {'a': 1, 'b': 3, 'c': 4, 'd':2}

How could I combine the values in python where these are not equal and if equal keep the same?

Expected output:

z = {'a': 1, 'b': 2 to 3, 'c': 3 to 4, 'd':2}

Solution

  • Assuming the keys are identical in the two dictionaries, use a dictionary comprehension with a conditional:

    z = {k: v - y[k] if v != y[k] else v for k, v in x.items()}
    

    Output: {'a': 1, 'b': -1, 'c': -1, 'd': 2}

    edited answer

    For a tuple:

    z = {k: (v, y[k]) if v!=y[k] else v for k, v in x.items()}
    

    Output: {'a': 1, 'b': (2, 3), 'c': (3, 4), 'd': 2}

    And a string:

    z = {k: f'{v} to {y[k]}' if v!=y[k] else v for k, v in x.items()}
    

    Output: {'a': 1, 'b': '2 to 3', 'c': '3 to 4', 'd': 2}

    generic approach for an arbitrary number of dictionaries

    dicts = [x, y]
    
    out = {}
    for d in dicts:
        for k, v in d.items():
            out.setdefault(k, set()).add(v)
    
    out = {k: ', '.join(map(str, v)) for k, v in out.items()}
    

    Output: {'a': '1', 'b': '2, 3', 'c': '3, 4', 'd': '2'}