0

I've been wondering why this does not work. It intrigued me enough to ask a question.

some_list = []
some_dict = {}
some_list.append(some_dict.update({'new_key': 'new_value'}))
print(some_list)

result: [None]

I would have thought the inner most strategies are evaluated first.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
David
  • 34,836
  • 11
  • 47
  • 77
  • 1
    It does 'work' though... `dict.update()` returns `None` and changes the dictionary in place. And the dictionary is updated. So everything seems okay. – Matt Hall Sep 13 '19 at 16:02

2 Answers2

5

some_dict.update updates some_dict in-place and returns None, it doesn't return the updated dict:

some_dict.update({'new_key': 'new_value'})
some_list.append(some_dict)

However, if you want to keep the old dict unchanged, you can use the following:

some_list = []
some_dict = {'old_key' : 'old_value'}
some_list.append({k : v for k, v in [*some_dict.items(), ('new_key', 'new_value')]})
print(some_list)
print(some_dict)

Output:

[{'old_key': 'old_value', 'new_key': 'new_value'}]
{'old_key': 'old_value'}
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
2

The problem is that update mutates the dictionary it is not returning a dictionary. See in the docs that this method returns None.

If you just want to have one line to solve your problem, you can solve this problem by:

some_list.append(dict({'new_key': 'new_value'}, **some_dict))

Also to keep in mind:

In Python 3.5+ you can do:

>>> params = {'a': 1, 'b': 2}
>>> new_params = {**params, **{'c': 3}}
>>> new_params
{'a': 1, 'b': 2, 'c': 3}

The Python 2 equivalent is:

>>> params = {'a': 1, 'b': 2}
>>> new_params = dict(params, **{'c': 3})
>>> new_params
{'a': 1, 'b': 2, 'c': 3}
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228