Python中的迭代器

时间:2014-11-23 18:21:51

标签: python dictionary

这是一个简单的嵌套字典:

wordFrequency = {'bit':{1:3,2:4,3:19,4:0},'red':{1:0,2:0,3:15,4:0},'dog':{1:3,2:0,3:4,4:5}}

我正在尝试解决这两段代码之间的区别:

for word, innerDictionary in wordFrequency.iteritems():
    for fileNum, appearances in innerDictionary.iteritmes():

for fileNum, appearances in wordFrequency.get(word, {}).iteritems():

我知道第一个允许我分别将内部字典的键和值分配给fileNum和外观。

但是,我不清楚第二段代码是否也一样?

1 个答案:

答案 0 :(得分:0)

以下命令:

for fileNum, appearances in wordFrequency.get(word, {}).iteritems():

只给你一个(嵌套字典的)值,但是如果你想要它和你前面的代码有相同的效果,因为get()的函数第一个参数必须是你需要的字典的一个键获取密钥并将代码放在循环中:

for word in  wordFrequency.keys() :
   for fileNum, appearances in wordFrequency.get(word, {}).iteritems():