在Javascript中是否有python 2.7x中的Object spread语法?

Mat*_*ood 15 javascript python object spread-syntax

如何将objects/dict(?)属性传播到新的object/dict中?

简单的Javascript:

const obj = {x: '2', y: '1'}
const thing = {...obj, x: '1'}
// thing = {x: '1', y: 1}
Run Code Online (Sandbox Code Playgroud)

蟒蛇:

regions = []
for doc in locations_addresses['documents']:
   regions.append(
        {
            **doc, # this will not work
            'lat': '1234',
            'lng': '1234',

        }
    )
return json.dumps({'regions': regions, 'offices': []})
Run Code Online (Sandbox Code Playgroud)

jua*_*aga 18

如果你有Python> = 3.5,你可以在dict文字中使用关键字扩展 :

>>> d = {'x': '2', 'y': '1'}
>>> {**d, 'x':1}
{'x': 1, 'y': '1'}
Run Code Online (Sandbox Code Playgroud)

这有时被称为"喷溅".

如果您使用的是Python 2.7,那么就没有相应的东西.这是使用超过7年的东西的问题.你必须做的事情如下:

>>> d = {'x': '2', 'y': '1'}
>>> x = {'x':1}
>>> x.update(d)
>>> x
{'x': '2', 'y': '1'}
Run Code Online (Sandbox Code Playgroud)


Mat*_*ero 7

dict您可以通过基于原始键创建一个,然后对新的/覆盖的键进行参数解包来实现这一点:

regions.append(dict(doc, **{'lat': '1234', 'lng': '1234'}))
Run Code Online (Sandbox Code Playgroud)

注意:适用于 python 2 和 python 3