Python dict歧义

Roh*_*yal -2 python dictionary loops list python-3.x

我想使用Python关键字dict返回一个字典,其中每个单词都是给定句子的真值。该代码段是:

return dict((word, True) for word in words)
Run Code Online (Sandbox Code Playgroud)

现在,当两个代码返回相同的字典时就会出现歧义:

1。

return dict((word, True) for word in words)
Run Code Online (Sandbox Code Playgroud)

2。

return dict([(word, True) for word in words])
Run Code Online (Sandbox Code Playgroud)

为什么第二个代码段不返回包含单词列表的字典?

Art*_*yer 5

这两个摘要在本质上与以下内容相同:

return dict.fromkeys(words, True)
Run Code Online (Sandbox Code Playgroud)

这是一个映射,其中键是项,words值是True。

dict类还需要一个迭代的(key, value)对,这是您要创建在这两个片段的内容。

在第一个中,它是一个生成器表达式,因此并非所有项都立即创建,而是在迭代时创建。

第二种是列表压缩,因此首先创建一个列表,然后创建所有项目并将其放入列表中。

无论哪种情况,都dict看到一个可迭代的。