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:
{'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. Instead, move it out