2014-04-02 88 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] 
相關問題