【问题标题】:iterating and printing words in a python dictionary在 python 字典中迭代和打印单词
【发布时间】:2014-12-13 03:48:18
【问题描述】:

我正在学习 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], " }")

我当前的打印语句不起作用,我找不到使用多个变量的大型打印语句的好例子。我该如何正确打印?

【问题讨论】:

  • “不起作用”是什么意思?如果您向我们提供 MCVE 会有所帮助,或者提供 test.txt 的内容,或者更好的是,提供刚刚在源代码中定义的 words。然后你可以显示预期和实际的输出。

标签: python dictionary output


【解决方案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)) 

【讨论】:

  • 谢谢!我正在尝试解决一些基本的 python 问题来处理它,我还有很多东西要学习。
【解决方案2】:

你可以使用dict.get,可以消除try和except块。

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)

【讨论】:

    【解决方案3】:

    像您在此处所做的那样遍历字典的最佳方法是按键 AND 值循环,每次通过循环解包键值元组:

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

    顺便说一句,在构建数组的那个循环中,您实际上并不需要那种异常处理逻辑。如果键不在字典中,字典的 get() 方法可以返回默认值,从而将您的代码简化为:

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

    【讨论】:

    • 我收到以下错误:ValueError: too many values to unpack (expected 2)
    • 这是错误的。当您迭代 dict 时,您只会得到它的键,而不是它的键值对。如果您想要后者,则必须使用 items 方法(如我的回答中所述)。此外,这并不能真正解释他的代码有什么问题。如果您将他的代码翻译为使用items,它将是for item, word in words.items():,然后是print 调用中的word[0],您会得到与他开始时完全相同的错误。
    • 固定使用items()。鉴于您这样做,我认为我不必特别解释为什么 OP 的代码是错误的。在我看来,我在这个答案中提供的代码是最好的方法;这是因为它读起来更惯用。当我最初发布答案时,我突然想到需要items()
    猜你喜欢
    • 1970-01-01
    • 2017-07-02
    • 2014-05-29
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 2015-07-05
    相关资源
    最近更新 更多