python - 向字典添加键和值

标签 python python-2.7 dictionary iteration

我正在尝试向(空)字典中添加一个新的键/值对。我有一个包含字符串(年)的文本文件,脚本应该计算年份的出现次数。

    with open ("results/results_%s.txt" % bla, "r") as myfile:
       for line in myfile:
        line = line.translate(None, ''.join(chars_to_remove))
        abc = line.split("_", 2)
        year = abc[1:2]
        year = ''.join(year)
        year = year.translate(None, ''.join(chars_to_remove))
        raey = {}
        #increment the value of the "year"-key, if not present set it to 0 to avoid key erros
        raey[year] = raey.get(year, 0) + 1

但是,如果这返回例如 {'2004': 1},但它应该已经构建了一个字典(如 {1993 : 2, 2012 : 3}),如果我在 for 循环中插入一个“打印”语句我得到例如:

{'1985': 1}
{'2062': 1}
{'1993': 1}
{'2000': 1}
{'2007': 1}
{'2009': 1}
{'1993': 1}
{'1998': 1}
{'1993': 1}
{'1998': 1}
{'2000': 1}
{'2013': 1}
{'1935': 1}
{'1999': 1}
{'1998': 1}
{'1992': 1}
{'1999': 1}
{'1818': 1}
{'2059': 1}
{'1990': 1}

它没有构建正确的字典,代码正在用每个循环替换字典。我做错了什么?

最佳答案

问题是您在 for 循环中初始化 dict,因此每次都会创建一个新的。相反,将其移出

with open ("results/results_%s.txt" % bla, "r") as myfile:
  raey = {}
  for line in myfile:
    line = line.translate(None, ''.join(chars_to_remove))
    abc = line.split("_", 2)
    year = abc[1:2]
    year = ''.join(year)
    year = year.translate(None, ''.join(chars_to_remove))
    #increment the value of the "year"-key, if not present set it to 0 to avoid key erros
    raey[year] = raey.get(year, 0) + 1

关于python - 向字典添加键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30728790/

相关文章:

python - 如何在 Django View 中显示 PDF 文件?

python - 在 wx 中绘制抗锯齿线?

python - 为什么 BeautifulSoup (在 Python 脚本中)只返回 HTML 中的一些数字

python - 如何通过多个键对数组进行分组?

python - 如何将不同的模型添加到 ModelForm 作为额外字段?

python - 屏蔽图像,其中屏蔽像素存在于像素值列表中

python - python 2.7.3 中的函数和参数

python - 删除所有内容,但保留数字和点

python - 删除字典中列表中的所有值

c# - 使用 GetHashCode 方法扩展接口(interface),用作通用字典中的键 (C#)