【问题标题】:Add key and value to dictionary向字典添加键和值
【发布时间】:2015-08-24 01:53:57
【问题描述】:

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

    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},但如果我在 for 循环中插入“打印”语句,它应该构建一个字典(如 {1993 : 2, 2012 : 3} )例如:

{'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}

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

【问题讨论】:

  • 您能否显示结果文件的上下文以帮助我们?在循环之外创建字典,否则您将在每个循环中重置它。
  • 您正在使用 raey = {} 每次迭代创建一个新的 raey 字典。将 if 放在 for 语句之前。
  • 阅读内置的collections 模块,尤其是Counterdefaultdict

标签: python python-2.7 dictionary iteration


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

【讨论】:

    【解决方案2】:

    您调用raey = {} 的每次迭代都会清除字典。将该行移到循环之前以初始化字典一次并将其填充到循环中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-10
      • 2022-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      相关资源
      最近更新 更多