在Python的字典文字中调用方法

时间:2014-06-09 22:28:39

标签: python dictionary list-comprehension

我正在尝试连接一些词典。我提出的最佳方法是使用dict1.update(dict2)

这是我正在尝试运行的代码,但它的计算结果为None。为什么呢?

{k:30 for k in [4, 9, 11, 6]}.update({k:31 for k in [1, 3, 5, 7, 8, 10, 12]})

2 个答案:

答案 0 :(得分:4)

dict.update方法就地工作,因此始终返回None。它与其他就地方法(例如dict.clearlist.append

没有什么不同

另请注意,docs中提到了此行为:

  

update([other])

     

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

强调我的。

答案 1 :(得分:1)

由于update没有返回对更新字典的引用,因此您可以使用以下代码:

import itertools
d = dict(itertools.chain({k:30 for k in [...]}.items(),
                         {k:31 for k in [...]}.items()))