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

2024-06-01 05:05:26 发布

您现在位置:Python中文网/ 问答频道 /正文

假设,如果我有一个口述词

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}}

通过这种方式,我将避免每次存储冗余项,而是使用一个较小的字典,只显示新添加的项

这种字典操作有很多实际用途,但不幸的是更难

如有任何帮助,我们将不胜感激


Tags: apple字典方式red结构whiteflowerfruit
1条回答
网友
1楼 · 发布于 2024-06-01 05:05:26

使用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}')

相关问题 更多 >