python 2.7x 中是否有像 Javascript 中那样的对象传播语法?

Is there an Object spread syntax in python 2.7x like in Javascript?

如何将 objects/dict(?) 属性扩展到新的 object/dict?

简单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': []})

您可以通过在原始的基础上创建一个 dict,然后对 new/overridden 键进行参数解包来实现此目的:

regions.append(dict(doc, **{'lat': '1234', 'lng': '1234'}))

注意: 在 python 2 和 python 3

中均有效

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

>>> 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'}