将具有相同键和值的词典合并到单个词典中

时间:2017-08-08 20:53:36

标签: python-2.7 list-comprehension dictionary-comprehension

我有一个字典,里面有一个列表,如下所示:

{"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"}}]}

有没有办法可以合并每个"数字"的项目?将值按值匹配到像这样的列表中?

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

1 个答案:

答案 0 :(得分:0)

我能想到实现这一目标的最简单方法是对所有项目进行排序'到一个中间词典,按“'数字”分组。从那里,将字典转换为所需的输出是微不足道的。

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()]}

输出:

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