从字典数组中提取重复项

2024-05-29 03:38:12 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有一组字典,看起来像这样:

books = [
         {'Serial Number': '3333', 'size':'500', 'Book':'The Hobbit'},
         {'Serial Number': '2222', 'size':'100', 'Book':'Lord of the Rings'},
         {'Serial Number': '1111', 'size':'200', 'Book':'39 Steps'},
         {'Serial Number': '3333', 'size':'600', 'Book':'100 Dalmations'},
         {'Serial Number': '2222', 'size':'800', 'Book':'Woman in Black'},
         {'Serial Number': '6666', 'size':'1000', 'Book':'The Hunt for Red October'},
        ]

我需要创建一个单独的dict数组,该数组基于重复的序列号,如下所示:

duplicates = [
    '3333', [{'Book':'The Hobbit'}, {'Book':'100 Dalmations'}],
    '2222', [{'Book':'Lord of the Rings'}, {'Book':'Woman in Black'}]
]

有没有一种简单的方法可以使用内置函数来实现这一点,如果没有,最好的方法是什么?你知道吗


Tags: oftheinnumbersizeserial数组black
1条回答
网友
1楼 · 发布于 2024-05-29 03:38:12

我能想到的最疯狂的方式是:

from collections import defaultdict
res = defaultdict(list)

for d in books:
    res[d.pop('Serial Number')].append(d)

print({k: v for k, v in res.items() if len(v) > 1})

输出:

{'2222': [{'Book': 'Lord of the Rings', 'size': '100'},
          {'Book': 'Woman in Black', 'size': '800'}],
 '3333': [{'Book': 'The Hobbit', 'size': '500'},
          {'Book': '100 Dalmations', 'size': '600'}]}

相关问题 更多 >

    热门问题