0

I'm using Python 2.7 and I want to use something as Javascript spread operator.

I have followin code:

def some_function():
  return {
        'a': "test",
        'b': 1,
        'c': 2
    } 

mapper = some_function()

test = mapper.update({'a': "Updated"})

print(test)

The result that I want is:

{
   'a': "Updated",
   'b': 1,
   'c': 2
}

But I get None instead.

Any idea?

userS
  • 67
  • 6
Boky
  • 11,554
  • 28
  • 93
  • 163
  • 2
    test mapps to the return of mapper.update. Try to print(mapper) instead – Ramon Medeiros Nov 14 '19 at 13:36
  • 1
    `mapper` is now updated, see `print(mapper)`. Are you saying you want `test` to have the updated `a` without changing `mapper`? – deceze Nov 14 '19 at 13:36
  • @deceze Yes, that is what I want. – Boky Nov 14 '19 at 13:38
  • The general design rule in Python is: If a function operates on an already existing object, that object will not be returned. This is called an in-place operation. – Klaus D. Nov 14 '19 at 13:38
  • they python doc is your friend https://docs.python.org/2/library/stdtypes.html#dict.update it tells `Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.` So it updates the object you gave it, it doesnt return you the update. – Chris Doyle Nov 14 '19 at 13:41

1 Answers1

0

dict.update happens in place so returns None so don’t assign the result to a variable.

mapper = some_function()
mapper.update({'a': "Updated"})
print(mapper)
#{'a': "Updated", 'b': 1, 'c': 2}

Or if you want to keep mapper but assign the updated value you can make a new dict using star unpacking:

test = {**mapper, 'a': 'Updated'}
Jab
  • 26,853
  • 21
  • 75
  • 114