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

问题描述 投票:10回答:2

如何将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': []})
javascript python object spread-syntax
2个回答
13
投票

如果你有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'}

2
投票

你可以通过创建一个基于原始的dict,然后为new / overriden键进行参数解包来实现这一点:

regions.append(dict(doc, **{'lat': '1234', 'lng': '1234'}))
© www.soinside.com 2019 - 2024. All rights reserved.