如何将一个对象/字典(?)的属性扩展到一个新的对象/字典中?
简单的 Javascript:
const obj = {x: '2', y: '1'}
const thing = {...obj, x: '1'}
// thing = {x: '1', y: 1}
python :
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
literal 中使用关键字扩展:
>>> d = {'x': '2', 'y': '1'}
>>> {**d, 'x':1}
{'x': 1, 'y': '1'}
这有时被称为“splatting”。
如果您使用的是 Python 2.7,那么没有对应的版本。这就是使用超过 7 年历史的问题。您必须执行以下操作:
>>> d = {'x': '2', 'y': '1'}
>>> x = {'x':1}
>>> x.update(d)
>>> x
{'x': '2', 'y': '1'}
关于javascript - Python 2.7x 中是否有像 Javascript 中那样的对象传播语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47875815/