2014-12-13 130 views
0

我正在学习python,我喜欢在少量代码中完成多少操作,但是我对语法感到困惑。我只是试图遍历字典并打印出每个项目和值。在python字典中迭代和打印单词

这里是我的代码:

words = {} 
value = 1 

for line in open("test.txt", 'r'): 
    for word in line.split(): 
     print (word) 
     try: 
      words[word] += 1 
     except KeyError: 
      #wur you at key? 
      print("no") 
      words[word]=1 

for item in words: 
    print ("{",item, ": ", words[item][0], " }") 

我当前的打印语句不工作,我无法找到使用多变量大print语句的一个很好的例子。我将如何正确打印?

+0

你说的意思是什么“不工作”?如果你向我们提供了一个[MCVE](http://stackoverflow.com/help/mcve),或者用'test.txt'的内容,或者更好的是用源代码中定义的'words',这将会有所帮助。然后你可以显示预期的和实际的输出。 – abarnert 2014-12-13 03:51:54

回答

1

您的问题似乎是,你要打印words[item][0],但words[item]总是将成为一个号码,并且号码不能被索引。

所以,只是......不要做:

print ("{",item, ": ", words[item], " }") 

这足以解决它,但有办法,你可以改善这个代码:

  • print有多个参数在每个空间之间放置一个空间,所以当你可能不想要所有这些空间时,你将最终打印{ item : 3 }。您可以通过使用关键字参数sep=''来解决该问题,但更好的解决方案是使用字符串格式或%运算符。
  • 您可以通过遍历words.items()而不是words来同时获取密钥和值。
  • 通过使用setdefault方法或使用defaultdict或更简单地说,您可以使用Counter来简化整个“存储默认值(如果其中一个不存在的话)”。
  • 您应该始终关闭打开的文件 - 最好使用with语句。
  • 要保持风格一致 - 不要在一些功能之后放置空格,但不要放置其他空间。

所以:

import collections 
with open("test.txt") as f: 
    words = collections.Counter(word for line in f for word in line.split()) 
for item, count in words.items(): 
    print("{%s: %d}" % (item, count)) 
+0

谢谢!我试图解决一些基本的python问题来处理它,并且我还有很多东西需要学习。 – 2014-12-13 04:10:18

-1

通过,你在这里做一个字典迭代,最好的办法是通过循环键和值,通过循环每次开箱键值元组:

for item, count in words.items(): 
    print("{", item, ": ", count, "}") 

而作为一个侧面说明,在构建数组的那个循环中,您并不需要那种异常处理逻辑。如果该键不在字典词典get()方法可以返回一个默认值,简化您的代码如下:

words[word] = words.get(word, 0) + 1 
+0

我收到以下错误:'ValueError:太多的值解压缩(预期2)' – 2014-12-13 03:55:17

+0

这是错误的。当你迭代一个'dict'时,你只需要得到它的键,而不是它的键 - 值对。如果你想要后者,你必须使用'items'方法(正如我的答案中所解释的)。另外,这并不能解释他的代码有什么问题;如果您将他的代码翻译为使用'items',则它将是'item',word.items():',然后是'print'调用中的word [0]',并且您会得到完全相同的他开始的错误。 – abarnert 2014-12-13 04:00:32

+0

固定使用'items()'。我认为我不必特别解释为什么OP的代码是错误的,因为你这样做。在我看来,我在这个答案中出现的代码是最好的方式;这是因为它更习惯地阅读。当我最初发布答案时,它已经放弃了我需要'items()'的想法。 – APerson 2014-12-13 04:03:48

0

可以使用dict.get并能消除尝试,除块。

words = {} 

for line in open("test.txt", 'r'): 
    for word in line.split(): 
     print (word) 
     words[word] = words.get(word,0) +1 

for word,count in words.items(): 
    print(word,count) 

dict.get它返回键,存在于词典否则默认值,如果
语法:dict.get(key[,default])

你也可以覆盖__missing__

class my_dict(dict): 
    def __missing__(self,key): 
     return 0 


words = my_dict() 

for line in open("test.txt", 'r'): 
    for word in line.split(): 
     print (word) 
     words[word] += 1 

for word,count in words.items(): 
    print(word,count)