如何将objects / dict(?)属性传播到新的object / dict中?
简单的Javascript:
const obj = {x: '2', y: '1'}
const thing = {...obj, x: '1'}
// thing = {x: '1', y: 1}
蟒蛇:
regions = []
for doc in locations_addresses['documents']:
regions.append(
{
**doc, # this will not work
'lat': '1234',
'lng': '1234',
}
)
return json.dumps({'regions': regions, 'offices': []})
如果你有Python >=3.5,你可以在dict
文字中使用关键字扩展:
>>> d = {'x': '2', 'y': '1'}
>>> {**d, 'x':1}
{'x': 1, 'y': '1'}
这有时被称为“喷溅”。
如果您使用的是Python 2.7,那么就没有相应的东西。这是使用超过7年的东西的问题。你必须做的事情如下:
>>> d = {'x': '2', 'y': '1'}
>>> x = {'x':1}
>>> x.update(d)
>>> x
{'x': '2', 'y': '1'}
你可以通过创建一个基于原始的dict
,然后为new / overriden键进行参数解包来实现这一点:
regions.append(dict(doc, **{'lat': '1234', 'lng': '1234'}))