Why does dict(k=4, z=2).update(dict(l=1)) return None in Python?

前端 未结 3 1281
别那么骄傲
别那么骄傲 2020-12-03 23:42

Why does dict(k=4, z=2).update(dict(l=1)) return None? It seems as if it should return dict(k=4, z=2, l=1)? I\'m using Python 2.7 shou

相关标签:
3条回答
  • 2020-12-04 00:37

    The .update() method alters the dictionary in place and returns None. The dictionary itself is altered, no altered dictionary needs to be returned.

    Assign the dictionary first:

    a_dict = dict(k=4, z=2)
    a_dict.update(dict(l=1))
    print a_dict
    

    This is clearly documented, see the dict.update() method documentation:

    Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

    0 讨论(0)
  • 2020-12-04 00:43

    dict.update() method does update in place. It does not return the modified dict, but None.

    The doc says it in first line:

    Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

    0 讨论(0)
  • 2020-12-04 00:48

    For completion's sake, if you do want to return a modified version of the dictionary, without modifying the original you can do it like this:

    original_dict = {'a': 'b', 'c': 'd'}
    new_dict = dict(original_dict.items() + {'c': 'f', 'g': 'h'}.items())
    

    Which gives you the following:

    new_dict == {'a': 'b', 'c': 'f', 'g': 'h'}
    original_dict == {'a': 'b', 'c': 'd'}
    
    0 讨论(0)
提交回复
热议问题