37

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': []})
Patrick Roberts
  • 44,815
  • 8
  • 87
  • 134
Armeen Harwood
  • 16,621
  • 30
  • 113
  • 222

2 Answers2

63

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'}
juanpa.arrivillaga
  • 77,035
  • 9
  • 115
  • 152
6

You can achieve this by creating a dict based on the original one, and then doing argument unpacking for the new/overridden keys:

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

Note: Works in both python 2 and python 3

Chandan
  • 10,375
  • 1
  • 5
  • 21
Matias Cicero
  • 23,674
  • 11
  • 73
  • 143