Add key and value to dictionary

129 views Asked by At

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?

2

There are 2 answers

0
Anshul Goyal On BEST ANSWER

The problem is you are initializing the dict within the for loop, so a new one is created everytime. 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
0
fhdrsdg On

Every iteration you call raey = {} which clears the dictionary. Move that line to before the loop to initialize the dictionary once and fill it in the loop.