简体   繁体   中英

Merging dictionaries in Python - doesn't work as expected

I'm looking for a way to merge dictionaries by other means than dict(a.items()+b.items()) is doing.

Example:

foo = {'cart':
  {'item':
    {'1':
      {'amount':
        'X',
      },
    },
  },
}

bar = {'cart': 
  {'item':
    {'2': 
      {'amount': 
        'Y',
      },
    },
  },
}

Wanted result:

res = {'cart':
  {'item':
    {'1':
      {'amount':
        'X'
      },
    },
    {'2': 
      {'amount': 
        'Y',
      },
    },
  },
}

Actual result (gotten bei dict(foo.items() + bar.items()):

res = {'cart':
  {'item':
    {'2': 
      {'amount': 
        'Y',
      },
    },
  },
}

Thanks a lot in advance!

Found that code snippet which does fairly well for my usecase:

def deepupdate(original, update):
    """
    Recursively update a dict.
    Subdict's won't be overwritten but also updated.
    """
    for key, value in original.iteritems():
        if not key in update:
            update[key] = value
        elif isinstance(value, dict):
            deepupdate(value, update[key])
    return update

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM