[英]Add key and value to dictionary
I am trying to add a new key/value pair to an (empty) dictionary. 我试图将新的键/值对添加到(空)字典中。 I have a text file with a string in it (years) and the script should count the appearances of the year.
我有一个带有字符串(年)的文本文件,脚本应该计算年份的出现。
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
However, if this returns for example {'2004': 1}, but It should have build a dictionary (like {1993 : 2, 2012 : 3} ), if I insert a "print" statement in the for loop I get for example: 但是,如果返回例如{'2004':1},但它应该建立一个字典(如{1993:2,2012:3}),如果我在for循环中插入“ print”语句,则得到例:
{'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}
It is not building a correct dict, the code is replacing the dict with every loop. 它没有建立正确的字典,代码正在用每个循环替换字典。 What am I doing wrong?
我究竟做错了什么?
The problem is you are initializing the dict within the for loop, so a new one is created everytime. 问题是您正在for循环中初始化dict,因此每次都会创建一个新字典。 Instead, move it out
相反,将其移出
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
Every iteration you call raey = {}
which clears the dictionary. 每次调用
raey = {}
将清除字典。 Move that line to before the loop to initialize the dictionary once and fill it in the loop. 将那条线移动到循环之前以初始化字典一次,并将其填充到循环中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.