【问题标题】:Merging dictionaries with the same key and values into a single dictionary将具有相同键和值的字典合并到一个字典中
【发布时间】:2017-08-08 20:53:36
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    我能想到的最简单的方法是将所有“项目”分类到一个中间字典中,按“数字”分组。从那里开始,将字典转换为所需的输出是微不足道的。

    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'}]}]}
    

    【讨论】:

    • 哇,这正是我需要的,非常感谢!在过去的一个小时里,我一直在试图解决这个问题。我想我应该多复习一下这个话题。
    猜你喜欢
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    相关资源
    最近更新 更多