36

如何将对象/字典(?)属性传播到新的对象/字典中?

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

2 回答 2

60

如果您有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'}
于 2017-12-18T20:25:09.943 回答
5

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

regions.append(dict(doc, **{'lat': '1234', 'lng': '1234'}))
于 2017-12-18T20:22:04.360 回答