Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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': []}) 
like image 241
Armeen Harwood Avatar asked Dec 18 '17 20:12

Armeen Harwood


People also ask

How do you spread an object in Python?

The JavaScript spread operator (...) is a useful and convenient syntax for expanding iterable objects into function arguments, array literals, or other object literals. Python contains a similar “spread” operator that allows for iterable unpacking.

Can you spread object JavaScript?

Object spread operator can be used to clone an object or merge objects into one. The cloning is always shallow. When merging objects, the spread operator defines new properties while the Object. assign() assigns them.

Can you spread an object into an array JavaScript?

Like the docs say, according to the "Rest/Spread Properties proposal", you can't spread object properties onto an array, objects will always spread their properties onto a new object. Likewise, arrays will not spread onto an object, they will only spread onto a new array.


1 Answers

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'} 
like image 132
juanpa.arrivillaga Avatar answered Sep 18 '22 11:09

juanpa.arrivillaga