2017-08-16 53 views
-7

只需要添加到數據庫區別data_out - 數據庫。Python區別兩個字典中的一個uniq鍵


如何添加到數據庫只有來自data_out(定期刷新)的新聞和數據庫沒有這個數據? db中的 必須沒有重複!


database = [ 
{ id: 1, name: 'steve', age: '18'}, 
{ id: 2, name: 'margo', age: '17'}, 
{ id: 3, name: 'sten', age: '19'} 
] 

data_from_out = [ 
{ name: 'steve', age: '18'}, 
{ name: 'margo', age: '17'}, 
{ name: 'sten', age: '19'}, 
{ name: 'janifer', age: '21'}, 
{ name: 'mary', age: '21'} 
] 

DIFF按名稱/標題(此uniq的PARAM),並加入到DB只差異。

添加到DB =>

{ "name": 'janifer', "age": '21'}, 
{ "name": 'mary', "age": '21'} 
. 

def compare_diff(arr_in, arr_database, check_tag): 
    try: 
     db_records = {d[check_tag] for d in arr_database} 
     data_from_out_records = {d[check_tag] for d in arr_in} 

     # set difference 
     diff = data_from_out_records - data_from_out_records & db_records 

     # make array from diff set 
     diff = [d for d in data_from_out_records if d[check_tag] if diff] 

     return diff 

    except: 
     print('Error in compare_diff. File file.py.') 
+0

請編輯你的答案,這是很不清楚你在問什麼。還請包括你已經試過的代碼 – dhdavvie

回答

0

diff你所描述是差集data_from_out_recordsdb_records之間

db_records = {d["name"] for d in database} 
data_from_out_records = {d["name"] for d in data_from_out} 
diff = data_from_out_records - data_from_out_records & db_records 
diff = [d for d in data_from_out if d["name"] if diff] 
+0

需要比較只有名稱 – ALPHA

+0

更容易,修復它。 如果我的答案有幫助,請接受它或至少投票 –

+0

print(diff)#set() 需要返回json數組 – ALPHA

0

工作代碼=>

def compare_diff(arr_in, arr_database, check_tag): 
    try: 
     db_records = {d[check_tag] for d in arr_database} 
     data_from_out_records = {d[check_tag] for d in arr_in} 

     # set difference 
     diff = data_from_out_records - (data_from_out_records & db_records) 

     # make array from diff set 
     diff_arr = [d for d in arr_in if d[check_tag] in diff] 

     return diff_arr 

    except: 
     print('Error in compare_diff') 
     return False 

感謝@ Uri-Goren的幫助。

相關問題