如何将字典列表分组为基于多个关键元素的唯一字典列表?你知道吗
in = [{'location': 'eastus', 'sku': 'S', 'term': 'P1', 'scope': '1'},
{'location': 'india', 'sku': 'a', 'term': 'P1', 'scope': '2'},
{'location': 'eastus', 'sku': 'S', 'term': 'P3', 'scope': '3'},
{'location': 'india', 'sku': 'f', 'term': 'P1', 'scope': '4'},
{'location': 'japan', 'sku': 'a', 'term': 'P1', 'scope': '5'},
{'location': 'india', 'sku': 'a', 'term': 'P3', 'scope': '6'}
]
关键元素是“location”和“sku”。我想将具有相同关键元素的字典分组到一个dict中,其中具有不同值的其余键将放入同一dict中的一个单独字典列表中
预期产量:
out = [{'location': 'eastus', 'sku': 'S', 'new_key': [
{'term': 'P1', 'scope': '1'},
{'term': 'P3', 'scope': '3'}
]},
{'location': 'india', 'sku': 'a', 'new_key': [
{'term': 'P1', 'scope': '2'},
{'term': 'P3', 'scope': '6'}
]},
{'location': 'india', 'sku': 'f', 'term': 'P1', 'scope': '4'},
{'location': 'japan', 'sku': 'a', 'term': 'P1', 'scope': '5'},
]
我试过this进行必要的修改,但我们有更好更准确的解决方案吗?你知道吗
使用
itertools.groupby
例如:
输出:
我已经修改了上面的答案,它给了我预期的结果。顺便说一句,谢谢@rakesh
您可以使用嵌套列表理解和一些讨厌的lambda来实现这一点:
测试在这里:https://ideone.com/24bjKw。然而,这个函数在这个过程中破坏了原始的
data
(调用原始dict的工作)。你知道吗内部lambda中的步骤链接是唯一棘手的部分:
使用
and
,因为pop
返回它所发现的内容,所以这种方式短路求值不能干扰i
将成为表达式的实际值。(如果对pop()
找到密钥有疑问,可能是i.pop("...",True)
)需要
or
,因为update()
返回None
(因此and
会在这里短路)。你知道吗剩下的只是打字。不幸的是,我不知道如何把它格式化成更好的形状。你知道吗
相关问题 更多 >
编程相关推荐