Search code examples
python-2.7list-comprehensiondictionary-comprehension

Merging dictionaries with the same key and values into a single dictionary


I have a dictionary with a list in it that looks like this:

{"items":[{"number":"98", "items": {"code": "X", "color": "Red"}},{"number":"98", "items": {"code": "Y", "color": "Blue"}},{"number":"62", "items": {"code": "B", "color": "Green"}}{"number":"62", "items": {"code": "A", "color": "Yellow"}}]}

Is there a way I could merge the items of each "number" that match by values together into a list like so?

{"items":[{"number":"98","items":[{"code":"X","color":"Red"}, {"code": "Y","color":"Blue"}]},  {"number":"62", "items": [{"code": "B", "color": "Green"},{"code": "A", "color":"Yellow"}]}]}

Solution

  • The easiest way that I could think of to accomplish this is to sort all of the 'items' into an intermediate dictionary, grouped by the 'number'. From there, transforming the dictionary into the desired output is trivial.

    inp = {"items":[{"number":"98", "items": {"code": "X", "color": "Red"}},{"number":"98", "items": {"code": "Y", "color": "Blue"}},{"number":"62", "items": {"code": "B", "color": "Green"}},{"number":"62", "items": {"code": "A", "color": "Yellow"}}]}
    d = dict()
    for i in inp['items']:
        d[i['number']] = d.get(i['number'], list()) + [i['items']]
    out = {'items': [{'number': n, 'items': d[n]} for n in d.keys()]}
    

    Output:

    {'items': [{'number': '98', 'items': [{'code': 'X', 'color': 'Red'}, {'code': 'Y', 'color': 'Blue'}]}, {'number': '62', 'items': [{'code': 'B', 'color': 'Green'}, {'code': 'A', 'color': 'Yellow'}]}]}