Python差异两个词典由一个uniq键

时间:2017-08-16 11:50:33

标签: python python-3.x difference

只需添加数据库差异data_out - 数据库。

如何只从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'}
 ]

按名称/标题差异(此uniq参数),并仅添加到数据库差异

添加到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.')

2 个答案:

答案 0 :(得分:0)

您所描述的diffdata_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]

答案 1 :(得分: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的帮助。