簡體   English   中英

合並基於一個鍵/值對的python詞典列表?

[英]Merging a list of dictionaries in python based on one key/value pair?

我在python 2.6中有兩個字典列表,我想根據對應於另一個鍵的一個鍵的最大值合並它們。 列表如下:

[{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}]

(項目的順序並不重要。)

換句話說,我想遍歷兩個列表,並獲取每個列表項的“顏色”,“形狀”和“優先級”的字典,其中對於每個“形狀”值,“優先級”的值最高)

幾天以來,我一直在搜索和嘗試SO上的其他事情,而我終於同意了。 我嘗試了各種版本的max,key,lambda等,但是在這里可以找到的所有線程似乎都不是我想要的。

提前致謝!

這是一個計划。 假定您不關心命令順序,但可以對其進行修改以關心命令。

讓我們看看我們有什么。 首先,結果字典來自哪個列表並不重要,因此我們可以將它們鏈接起來。 其次,從形狀相同的每組字典中,我們只選擇一個。 看起來我們需要按形狀對所有字典進行分組,然后為每個組選擇優先級最高的字典。

最明顯的方法是將collections.defaultdict分組,然后在列表推導中使用max選擇每個組中的最佳dict。 稍微棘手的是itertools.groupby形狀和優先級排序,然后按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]

只需對合並列表使用按優先級排序的新字典,即可將每個字典保存在合並列表中:

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

由於這是具有唯一鍵的字典,因此給定形狀的最后一個項目將替換具有相同形狀的較早的項目。 由於項目按優先級排序,因此res字典中的{'shape': 'square', 'color': 'red', 'priority': 2}{shape: square, color: green, priority: 3}替換{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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM