根据两个字典的差异创建字典

时间:2020-08-23 11:39:38

标签: python dictionary

假设我有字典,

dictA = {
         'flower': 
                 {
                  'jasmine': 10,
                  'roses': 
                        {
                         'red': 1,
                         'white': 2
                        }
                 },
        'fruit':
               {
                'apple':3
               }
        }

如果dictA已更新(例如更新为dictB

dictB = {
         'flower': 
                 {
                  'jasmine': 10,
                  'roses': 
                         {
                          'red': 1,
                          'white': 2
                         }
                 },
         'fruit':
                 {
                  'apple':3,
                  'orange': 4
                 }
        }

现在我将如何获取仅包含新添加的项(保留结构)的字典,类似

difference(dictB, dictA) = {'fruit': {'orange': 4}}

通过这种方式,我避免每次都存储多余的项目,而是使用较小的字典来仅显示新添加的项目

这种对词典的操纵有很多实际用途,但不幸的是,

任何帮助将不胜感激,在此先感谢

1 个答案:

答案 0 :(得分:2)

使用DictDiffer

from dictdiffer import diff, patch, swap, revert

dictA = {
         'flower':
                 {
                  'jasmine': 10,
                  'roses':
                        {
                         'red': 1,
                         'white': 2
                        }
                 },
        'fruit':
               {
                'apple':3
               }
        }

dictB = {
         'flower':
                 {
                  'jasmine': 10,
                  'roses':
                         {
                          'red': 1,
                          'white': 2
                         }
                 },
         'fruit':
                 {
                  'apple':3,
                  'orange': 4
                 }
        }

result = diff(dictA, dictB)

# [('add', 'fruit', [('orange', 4)])]
print(f'Diffrence :\n{list(result)}')

patched = patch(result, dictA)

# {'flower': {'jasmine': 10, 'roses': {'red': 1, 'white': 2}}, 'fruit': {'apple': 3}}
print(f'Apply diffrence :\n{patched}')