【问题标题】:Extracting duplicate from array of dictionaries从字典数组中提取重复项
【发布时间】:2014-04-27 17:09:52
【问题描述】:

您好,我有一个如下所示的 dicts 数组:

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

我需要根据重复的序列号创建一个单独的字典数组,如下所示:

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

有没有一种简单的方法可以使用内置函数来做到这一点,如果不是最好的方法是什么?

【问题讨论】:

  • 如果有超过 1 个重复项怎么办?
  • 好问题,我已经修改了我的问题以考虑到这一点!
  • 您的编辑不是有效的python数据结构。
  • 很好发现 - 已修复!
  • 仍然不太有效

标签: python arrays dictionary


【解决方案1】:

我能想到的最pythonic的方式:

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

【讨论】:

  • 这似乎运作良好。但是,我现在如何才能获得这种新结构中每本书的“大小”?
  • @user1513388 例如霍比特人:hobbit = [x for x in duplicates['2222'] if x['Book'] == 'The Hobbit'][0]。现在你可以得到这样的大小:hobbit['size']
猜你喜欢
  • 2017-02-28
  • 2022-11-21
  • 2018-06-27
  • 1970-01-01
  • 2018-05-15
  • 2018-11-04
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
相关资源
最近更新 更多