为什么dict(k = 4,z = 2).update(dict(l = 1))在Python中返回None?

时间:2013-08-03 22:14:07

标签: python python-2.7 dictionary

为什么dict(k=4, z=2).update(dict(l=1))会返回None?似乎它应该返回dict(k=4, z=2, l=1)?我应该使用Python 2.7。

3 个答案:

答案 0 :(得分:9)

.update()方法改变字典到位并返回None。字典本身被更改,不需要返回更改的字典。

首先分配词典:

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

这是清楚记录的,请参阅dict.update() method documentation

  

使用其他键中的键/值对更新字典,覆盖现有键。返回None

答案 1 :(得分:2)

dict.update()方法确实更新了。它不会返回修改后的字典,而是None

医生在第一行说:

  

使用其他键中的键/值对更新字典,覆盖现有键。 返回无。

答案 2 :(得分:1)

为了完成起见,如果你想要返回字典的修改版本而不修改原文,你可以这样做:

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

它为您提供以下内容:

new_dict == {'a': 'b', 'c': 'f', 'g': 'h'}
original_dict == {'a': 'b', 'c': 'd'}