【问题标题】:python: list of dict groupby based on similar keys and then filterpython:基于相似键的dict groupby列表然后过滤
【发布时间】:2020-06-10 19:26:38
【问题描述】:

我有一个字典列表,例如:

data = [
  {'11': {'x': 333, 'priority': 1, 'channels': 40}}, 
  {'11': {'x': 444, 'priority': 2, 'channels': 30}}, 
  {'22': {'x': 000, 'priority': 1, 'channels': 55}}
]

我想对具有相似键的 dict 元素进行分组,例如:

 [
   [{'11': {'x': 333, 'priority': 1, 'channels': 40}}, 
    {'11': {'x': 444, 'priority': 2, 'channels': 30}}], 
   [{'22': {'x': 000, 'priority': 1, 'channels': 55}}]
 ]

如果 group-by 列表中包含超过 1 个元素,则过滤名为 priority 的键上的 dict 元素。

期望的输出:

 [
   {'11': {'x': 333, 'priority': 1, 'channels': 40}}, 
   {'22': {'x': 000, 'priority': 1, 'channels': 55}}
 ]

【问题讨论】:

  • 是什么让您的示例中的元素“相似”?键11,还是下面数据里的什么东西?
  • @9000 键 11 使其相似。

标签: python-3.x list dictionary


【解决方案1】:
data = [
  {'11': {'x': 333, 'priority': 1, 'channels': 40}},
  {'11': {'x': 444, 'priority': 2, 'channels': 30}},
  {'22': {'x': 000, 'priority': 1, 'channels': 55}}
]

tmp = {}
for d in data:
    tmp.setdefault([*d][0], []).append(d)

out = [subl[0] for subl in tmp.values()]  
# to select min priority you can do:
# out = [min(subl, key=lambda k: k[[*k][0]]['priority']) for subl in tmp.values()]

# print it to screen:
from pprint import pprint
pprint(out)

打印:

[{'11': {'channels': 40, 'priority': 1, 'x': 333}},
 {'22': {'channels': 55, 'priority': 1, 'x': 0}}]

【讨论】:

  • 太棒了,你能解释一下吗?
  • @Jackma 我创建了临时字典tmp,在其中我通过键将列表data 中的元素分组(我用[*d][0] 提取键)。然后我通过从每个组中获取第一个子列表来制作输出列表。
  • 这段代码是否考虑了priority 的值?当您更改 '11' 字典的顺序时,您将获得 priority 2 而不是 priority 1。
【解决方案2】:

你可以试试

from collections import defaultdict

res = defaultdict(list)
for i in data:
    res[list(i.keys())[0]].append(i)
print([min(i, key=lambda x: list(x.values())[0]['priority']) for i in res.values()])

输出

[{'11': {'x': 333, 'priority': 1, 'channels': 40}}, {'22': {'x': 0, 'priority': 1, 'channels': 55}}]

defaultdict 将聚合所有具有相同键的字典,然后与min 函数的列表比较将按最低优先级返回字典。

【讨论】:

  • 这个答案对您有帮助吗?
【解决方案3】:

您可以使用循环来做到这一点:

result = []
for group in data:
    result.append(min(group, key=lambda x: list(x.values())[0]['priority']))

【讨论】:

  • 它给出了错误:result.append(max(group, key=lambda x: list(x.values())[0]['priority'])) AttributeError: 'str' object has no attribute 'values'
猜你喜欢
  • 1970-01-01
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 2019-11-20
  • 1970-01-01
  • 1970-01-01
  • 2016-07-31
  • 1970-01-01
相关资源
最近更新 更多