比较字典和输出差异的两个列表

时间:2018-08-29 20:46:43

标签: python python-2.7 dictionary

我有2个字典列表,我需要比较它们并输出报告的差异

我需要:

  1. 对照old_list检查new_list中是否有新记录(存在于new_list中但不存在于old_list中的记录),并将它们附加到Updated_list中
  2. 忽略匹配的记录(所有键,值均匹配)
  3. 查找具有不同event15或event16的匹配记录,并使用两个值的差异更新事件
  4. 将结果输出到新的字典列表(在此示例中为updated_list)

要处理:

new_list = [
{'datetime': '2018-08-01', 'evar1': 'newRecord', 'event16': '100', 'event15': '200'},
{'datetime': '2018-08-02', 'evar1': 'duplicateRecord', 'event16': '10', 'event15': '20'},
{'datetime': '2018-08-03', 'evar1': 'diffEvent', 'event16': '15', 'event15': '25'}
]

old_list = [
{'datetime': '2018-08-02', 'evar1': 'duplicateRecord', 'event16': '10', 'event15': '20'},
{'datetime': '2018-08-03', 'evar1': 'diffEvent', 'event16': '10', 'event15': '25'}
] 

结果应类似于以下列表:

updated_list = [
{'datetime': '2018-08-01', 'evar1': 'newRecord', 'evar3': 'site',  'event16': '100', 'event15': '200'},
{'datetime': '2018-08-03', 'evar1': 'diffEvent', 'evar3': 'site',  'event16': '5', 'event15': '25'}
]

我尝试过:

updated_list = []
for new_item in new_list:
    for old_item in old_list:
        for key, value in new_item.iteritems():
        # If values don't match, subtract old_list value from new_list values and append the diff
        if any(ko == key for ko, vo in old_item.iteritems()):
            ko, vo = [(ko, vo) for (ko, vo) in old_item.iteritems() if ko == key][0]
            if vo != value:
                new_value = value - vo
                new_item.update({ko: new_value})
                updated_list.append(new_item)
            else:
            # If record does not exist in old_list, append the new record
            updated_list.append(new_item)

1 个答案:

答案 0 :(得分:1)

确实非常令人困惑!这是我的解决方案(评论应解释该方法)。

index  A  B    C         D      (extra)   (extra)  (extra)  (extra)
  0    1  2  'abc\'    'def\'    'ghi\'    'jkl\'   'xyz'   some_date
  1    1  2  'abc'    some_date
  2    1  2  'abc\'    'def'    some_date

index  A  B         C                D
  0    1  2  'abcdefghijklxyz'   some_date
  1    1  2       'abc'          some_date
  2    1  2     'abcdef'         some_date