python 2.7x中是否有像Javascript一样的对象传播语法? [英] Is there an Object spread syntax in python 2.7x like in Javascript?
本文介绍了python 2.7x中是否有像Javascript一样的对象传播语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将对象/dict(?) 属性传播到新的对象/dict 中?
简单的Javascript:
const obj = {x: '2', y: '1'}const 东西 = {...obj, x: '1'}//东西 = {x: '1', y: 1}
蟒蛇:
regions = []对于locations_addresses['documents']中的文档:区域.附加({** doc, # 这行不通'纬度':'1234','lng': '1234',})返回 json.dumps({'regions': region, 'offices': []})
解决方案
如果你有 Python >=3.5,你可以在dict
字面量中使用关键字扩展:
这有时被称为喷溅".
如果您使用的是 Python 2.7,那么,没有等效项.这就是使用超过 7 年的东西的问题.您必须执行以下操作:
<预><代码>>>>d = {'x':'2','y':'1'}>>>x = {'x':1}>>>x.更新(d)>>>X{'x':'2','y':'1'}How can I spread an objects/dict(?) properties and into a new object/dict?
Simple 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': []})
解决方案
If you had Python >=3.5, you can use key-word expansion in dict
literal:
>>> d = {'x': '2', 'y': '1'}
>>> {**d, 'x':1}
{'x': 1, 'y': '1'}
This is sometimes referred to as "splatting".
If you are on Python 2.7, well, there is no equivalent. That's the problem with using something that is over 7 years old. You'll have to do something like:
>>> d = {'x': '2', 'y': '1'}
>>> x = {'x':1}
>>> x.update(d)
>>> x
{'x': '2', 'y': '1'}
这篇关于python 2.7x中是否有像Javascript一样的对象传播语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文