首页 > 解决方案 > 用另一张地图更新地图

问题描述

在 groovy 中,我想用另一个更新(左合并)一个地图。

def item = [attributes:[color:'Blue', weight:500], name:'hat', price:150]
def itemUpdate = [attributes:[size: 10]]
item << itemUpdate
println item

给出:

[属性:[尺寸:10],名称:帽子,价格:150]

但我想要的是:

[属性:[颜色:'蓝色',重量:500,尺寸:10],名称:'帽子',价格:150]

我也试过:

item += itemUpdate

或使用从地图更新 groovy 对象字段。没有一个能满足我的要求;在python中,方法就是update()方法。

编辑:实际上我对 python 的看法是错误的。

标签: dictionarygroovy

解决方案


你正在做的是有效地覆盖attributes条目。

相反,您想要做的是:

item.attributes = item.attributes + itemUpdate

你甚至可以这样做:

item.attributes += itemUpdate

两者都产生了预期

[attributes:[color:Blue, weight:500, size:10], name:hat, price:150]

推荐阅读