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

标签 javascript python object spread-syntax

如何将一个对象/字典(?)的属性扩展到一个新的对象/字典中?

简单的 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/

相关文章:

javascript - ReactJS 仅在焦点/更改时为价格添加逗号

javascript - 解析: Add user to role using cloud code

python - 无法使用 unittest 修补由测试类实例化的类

javascript - 需要一种有效的方法来对 javascript 中的对象数组进行分组

java - 在 Java 中通过类型转换分配属性值

java - Hibernate 和 Thymeleaf 无限递归

javascript - 将 HTML 提取到 <div> 中并覆盖内容

python - 测试断言HTTP 400

python - 让我的 Python 代码第一次运行的好方法是什么?

javascript - 如何中断 javascript 对象引用