亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據兩個字典的不同創建字典

根據兩個字典的不同創建字典

HUH函數 2023-06-13 15:34:47
假設,如果我有一本字典,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 回答

?
四季花海

TA貢獻1811條經驗 獲得超5個贊

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


查看完整回答
反對 回復 2023-06-13
  • 1 回答
  • 0 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號