I get: "object does not support item assignment" when populating a dictionary

11,216
# this is a dict 
#   ↓
evanrate = {}                                                # this isn't  --.
                                                             #     ↓         |
with open(r'C:\Users\Jeroen\documents\hacker1\evanrate.csv') as evanrate:  # |
        parsereader = csv.reader(evanrate, delimiter = ';')                # |
    for row in parsereader:                                                # |
        fips = row[0]                                                      # |
        rate = float(row[1].replace(',', '.'))                             # /
        #   ↓---------------------------------------------------------------/
        evanrate[fips] = rate

Rename either your dict or your file.

Share:
11,216
Admin
Author by

Admin

Updated on June 14, 2022

Comments

  • Admin
    Admin almost 2 years

    I am new to Python and programming, and am currently working on a script that will eventually colour counties in a US map according to the rate of protestantism. I have run into a problem that has left me dumbfounded, and I can't seem to find any answers.

    This code reads in a csv file which has the following format:

    2060;6,018888889
    2068;169,77
    etc...
    

    Where the first item is the fips code, and the second is the rate. I want to assign these to a dictionary, which I can later use to colour in the counties map. The following code is meant to achieve just that:

    #populate dictionary with fips and rate from csv file
    evanrate = {}
    
    with open(r'C:\Users\Jeroen\documents\hacker1\evanrate.csv') as evanrate:
            parsereader = csv.reader(evanrate, delimiter = ';')
        for row in parsereader:
            fips = row[0]
            rate = float(row[1].replace(',', '.'))
    
            evanrate[fips] = rate
    

    However, when I try to fill in the dictionary using the code "evanrate[fips] = rate", I get the error:

    Traceback (most recent call last):
       File "C:\Users\Jeroen\Documents\hacker1\evanrate.py", line 16, in <module>
        evanrate['fips'] = rate
       TypeError: '_io.TextIOWrapper' object does not support item assignment
    

    I am using Python 3.3 and Windows 7.

  • Admin
    Admin about 11 years
    Thanks a lot for the solution. Was quite an simple mistake after all.
  • user427969
    user427969 almost 10 years
    Thanks a lot. I was getting this error because I had same name for a method and a class attribute