2016-12-05 156 views
0

好的排列, 我想合併兩個字典列表,如果它們具有相同的鍵:值。它就像SQL中的連接一樣。我不允許爲這個問題導入任何模塊。合併具有相同鍵的兩個字典列表:

下面的例子:

輸入:

>>> series = [ 
... {'s_id': 'bb', 'title': 'Breaking Bad'}, 
... {'s_id': 'bcs', 'title': 'Better Call Saul'}] 

>>> series_characters = [ 
... {'c_id': 'ww', 's_id': 'bb'}, 
... {'c_id': 'sw', 's_id': 'bb'}, 
... {'c_id': 'sg', 's_id': 'bb'} 
... {'c_id': 'sg', 's_id': 'bcs'} 

輸出應類型的字典中既infomration裏面的清單:

out= [ 
{'s_id': 'bb', 'title': 'Breaking Bad', 'c_id': 'ww'}, 
{'s_id': 'bcs', 'title': 'Better Call Saul', 'c_id': 'sg'}] 

我嘗試財產以後這樣的,但我認爲,我的想法是複雜的,代碼doesen't工作:

def _join(tbl1, tbl2): 
    """ 
    Helping function to merge two tables inform of a list 

    Argurments: 
     tbl1 (list): list of dict's containung a table 
     tbl2 (list): list of dict's containung a table 
    Returns: 
     back_lst (list): list, containing wanted rows of the table 

    """ 
    back_lst = [] 
    for element1 in tbl1: 
     for element2 in tbl2: 
      for key in tbl1[element1]: 
       if tbl1[element1[key]] == tbl2[element2[key]]: 
        a = tbl1[element1].copy() 
        a.update(tbl2[element2]) 
        back_lst.append(a) 
    return back_lst 

這將很高興在這裏得到一些幫助。提前致謝。

+1

in series_charachter for s_id bb,c_id是ww,sw,sg那麼爲什麼它只與sg合併而不是其他的? – harshil9968

+0

@ harshil9968好點,還應該注意,如果有多於一個的常用鍵,例如在SQL中,tbl1.name = tbl2.name和tbl1.id = tbl2.id。 –

回答

0

你不想做tbl1[element1],假設tbl1是一個字典列表。 element1應該已經是你想要的字典,所以只需要element1.copy()。索引編號tbl2相同。

+0

你是對的,謝謝你的提示! –

3

鑑於所有的按鍵都只是字符串,你可以這樣做:

>>> [dict(a, **b) for a in series_characters for b in series if a['s_id'] == b['s_id']] 
[{'c_id': 'ww', 's_id': 'bb', 'title': 'Breaking Bad'}, 
{'c_id': 'sw', 's_id': 'bb', 'title': 'Breaking Bad'}, 
{'c_id': 'sg', 's_id': 'bb', 'title': 'Breaking Bad'}, 
{'c_id': 'sg', 's_id': 'bcs', 'title': 'Better Call Saul'}]​ 
0
# your code goes here 

def joinTable(tbl1, tbl2): 
    op = [] 
    if len(tbl1) > 0 and len(tbl2) > 0: 
     keys = set(tbl1[0].keys()).intersection(tbl2[0].keys()) 
     opkeys = set(tbl1[0].keys()).union(tbl2[0].keys()) 
     for row1 in tbl1: 
      key1 = set(row1.keys()) 
      for row2 in tbl2: 
       key2 = set(row2.keys()) 
       assert key1.intersection(key2) == keys 
       assert key1.union(key2) == opkeys 
       match = True 
       for key in keys: 
        match = row1[ key] == row2[key] 
       if match: 
        d = dict() 
        for key in opkeys: 
         d[ key ] = row1[ key ] if key in row1 else row2[key] 
        op.append(d) 
    return op 

print joinTable([{'s_id': 'bb', 'title': 'Breaking Bad'},{'s_id': 'bcs', 'title': 'Better Call Saul'}],[ 
{'c_id': 'ww', 's_id': 'bb'},{'c_id': 'sw', 's_id': 'bb'}, {'c_id': 'sg', 's_id': 'bb'},{'c_id': 'sg', 's_id': 'bcs'}]) 

Ideone

它實現SQL的連接算法。類似於https://blogs.msdn.microsoft.com/craigfr/2006/08/03/merge-join/

您可以進一步擴展它以像特定的鍵和限制值一樣。