-1

I am trying to merge between 2 dictionaries by using update() but I get "None" when I try to print the function's result

def merge_dictionaries(dict1,dict2):
     return dict1.update(dict2)

dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

print(merge_dictionaries(dict1,dict2))

why do I get None?

I tried to change the input values but nothing have changed/

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • 1
    `update` mutates an existing dictionary. It doesn't return a new one. It's not exactly a duplicate, but see [this question](https://stackoverflow.com/q/11205254/4996248) for a similar problem with lists. – John Coleman Jan 06 '23 at 20:04
  • 4
    The convention used by the standard library is to return `None` when a function or method modifies its argument or object in-place. – chepner Jan 06 '23 at 20:04
  • `dict.update` updates the dict in-place. If you want to return updated dict use `{**dict1, **dict2}` or `dict1 | dict2` in newer versions of python. Related [SO post](https://stackoverflow.com/q/38987) – Ch3steR Jan 06 '23 at 20:05
  • You're probably looking for `return {**dict1, **dict2}`. – AKX Jan 06 '23 at 20:05
  • "I tried to change the input values but nothing have changed/" they did change, check `print(dict1)` – juanpa.arrivillaga Jan 06 '23 at 20:10
  • 3
    Why are you expecting `.update()` to return something? Have you read the documentation for that method? – John Gordon Jan 06 '23 at 20:10

1 Answers1

1

The update() method does not return a new dictionary with the updates, it just updates the dictionary in place.

.

This way you return the dictionary that has been updated:

def merge_dictionaries(dict1,dict2):
     dict1.update(dict2)
     return dict1

.

You should also consider other methods to merge the dicts, such as

  • {**dict1, **dict2} syntax
  • ChainMap class from the collections module
  • dictionary comprehension
  • union() method from the merge_dict library
  • dict1 | dict2 syntax
Davi A. Sampaio
  • 374
  • 2
  • 12
  • "When you give values to a function, you are actually parsing a copy of the values. So on this code, the actual dictionaries are not being changed, only the copies" - this is totally wrong. The dict **is** updated. – Thierry Lathuille Jan 06 '23 at 20:12
  • @ThierryLathuille you are right, I made a confusion. The answer is updated – Davi A. Sampaio Jan 06 '23 at 20:16