2014-04-02 90 views
1

我有两个Python 2.6中的字典列表,我想根据与另一个键对应的一个键的最高值合并它们。该列表是这样的:基于一个键/值对合并python词典列表?

[{shape: square, color: red, priority: 2}, 
{shape: circle, color: blue, priority: 2}, 
{shape: triangle, color: green, priority: 2}] 

[{shape: square, color: green, priority: 3}, 
{shape: circle, color: red, priority: 1}] 

我想要得到这样的输出:(项目的顺序并不重要)

[{shape: square, color: green, priority: 3}, 
{shape: circle, color: blue, priority: 2}, 
{shape: triangle, color: green, priority: 2}] 

换句话说,我'想要通过这两个列表并且获得每个列表项目的'颜色','形状'和'优先级'的字典,其中'形状'的每个值的'优先'值是最高的)

我一直在寻找和在几天的时间里尝试不同的事情,并且我终于让步了。我已经尝试过各种版本的max,key,lambda等,但是我在这里可以找到的所有线程似乎都不是我正在寻找的。

在此先感谢!

+0

如何列表合并? –

回答

1

只需使用一个新的字典,按优先级排序,以合并后的名单保持每个字典在合并后的列表:

li1=[{'shape': 'square', 'color': 'red', 'priority': 2}, 
{'shape': 'circle', 'color': 'blue', 'priority': 2}, 
{'shape': 'triangle', 'color': 'green', 'priority': 2}] 

li2=[{'shape': 'square', 'color': 'green', 'priority': 3}, 
{'shape': 'circle', 'color': 'red', 'priority': 1}] 

res={} 
for di in sorted(li1+li2, key=lambda d: d['priority']): 
    res[di['shape']]=di 

print res.values() 

打印:

[{'color': 'blue', 'priority': 2, 'shape': 'circle'}, 
{'color': 'green', 'priority': 3, 'shape': 'square'}, 
{'color': 'green', 'priority': 2, 'shape': 'triangle'}] 

因为这是唯一身份键,胃肠道的最后一个项目的字典ven形状将取代具有相同形状的较早项目。由于这些项目按优先级排序,因此res字典中的{'shape': 'square', 'color': 'red', 'priority': 2}被替换为{shape: square, color: green, priority: 3},因为3> 2等等。

所以,你可以在Python 2.7+做到这一切在一个单一的线:

{di['shape']:di for di in sorted(li1+li2, key=lambda d: d['priority'])}.values() 
1

这是一个计划。它假定你不关心订单排序,但你可以修改它来关心。

让我们看看我们有什么。首先,从结果字典出现的清单并不重要,所以我们可以将它们链接起来。其次,从每一组具有相同形状的字典中我们选择一个。看起来我们需要按形状对所有字典进行分组,然后为每个分组选择一个具有最高优先级的字典。

显而易见的方法是与collections.defaultdict进行分组,然后在清单理解中使用max以在每个组中选择最佳字典。稍微更棘手的一个。将通过形状和负的优先级,按形状的第一排序与itertools.groupby,然后从每组中选择第一个元素:

from itertools import chain, groupby 

sorted_dicts = sorted(chain(list1, list2), 
         key=lambda d: (d['shape'], -d['priority'])) 
groups = groupby(sorted_dicts, key=lambda d: d['shape']) 
merged = [next(g) for _, g in groups] 
相关问题