2015-03-31 54 views
0

例如,在下面的列表中,我想合併所有共享相同'id'和'name'的字典。如何在基於相同鍵值對的數組中組合詞典?

輸入:

l = [{'id':'1','name':'a','key1':'1'}, 
    {'id':'1','name':'a','key2':'3'}, 
    {'id':'1','name':'a','key3':'4'}, 
    {'id':'2','name':'a','key5':'1'}, 
    {'id':'2','name':'a','key7':'c'}, 
    {'id':'1','name':'b','key5':'1'}] 

所需的結果:

l = [{'id':'1','name':'a','key1':'1','key2':'3','key3':'4'}, 
    {'id':'2','name':'a','key5':'1','key7':'c'}, 
    {'id':'1','name':'b','key5':'1'}] 

如果可能的話,我想的功能也採取不同數量的參數爲哪個鍵的字典將有機會分享他們結合。例如,如果我只是想基於'id'而不是'key'和'name'進行組合,結果將會不同。

+0

可能重複http://stackoverflow.com/questions/7327344/python-quickest-way-to-合併-詞典的基礎上琴鍵匹配) – 2015-03-31 10:33:58

回答

0

itertools.groupby爲您分組。所有剩下要做然後到字典(由ID分組)的iterables清單合併成一個字典列表:

>>> import itertools  
>>> l = [ dict(reduce(lambda a, b: a + b.items(), lst, [])) for lst in \ 
      [ list(grouper) for key, grouper in \ 
      itertools.groupby(l, lambda x: (x["id"], x["name"])) ] \ 
     ] 
>>> l 
[{'id': '1', 'key1': '1', 'key2': '3', 'key3': '4', 'name': 'a'}, 
{'id': '2', 'key5': '1', 'key7': 'c', 'name': 'a'}, 
{'id': '1', 'key5': '1', 'name': 'b'}] 

這顯然不是最可讀的版本做;你應該使用一個幫助函數來合併字典,而不是嵌套的列表解析。

0

傳統的方式:d

result = [] 

for item in l : 
    check = False 
    # check item, is it exist in result yet (r_item) 
    for r_item in result : 
     if item['id'] == r_item['id'] and item['name'] == r_item['name'] : 
      # if found, add all key to r_item (previous record) 
      check = True 
      r_item.update(item) 
    if check == False : 
     # if not found, add item to result (new record) 
     result.append(item) 
的[基於關鍵字匹配合並字典蟒蛇最快方式(
相關問題