Is there an object extension operator in python 2.7x, as in Javascript?

How can I extend the properties of / dict (?) Objects to a new / dict object?

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': []}) 
+5
source share
2 answers

If you have Python> = 3.5 , you can use the keyword extension in dict literal:

 >>> d = {'x': '2', 'y': '1'} >>> {**d, 'x':1} {'x': 1, 'y': '1'} 

This is sometimes called "splatting."

If you're on Python 2.7, well, there is no equivalent. This is a problem with using something for more than 7 years. You will need to do something like:

 >>> d = {'x': '2', 'y': '1'} >>> x = {'x':1} >>> x.update(d) >>> x {'x': '2', 'y': '1'} 
+7
source

You can achieve this by creating a dict based on the original, and then unzip the argument for new / redefined keys:

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

Source: https://habr.com/ru/post/1274171/


All Articles