Using Python I am trying to analyze a tab delimited file. I open the file and import as a list of dictionaries here:
import csv
fileIN = open('transaction_tmp', "r")
list_of_dicts = list(csv.DictReader(fileIN, dialect='excel-tab'))
I need to count (and note the row) for a particular column of this file. I create an empty dictionary:
dict_card = {}
And now I am trying to iterate through the list of dictionaries, and if a value is not noted, I note it (as the key) and for value set the row found (in the list of dictionaries). If it has already been added, I just add the row found:
for x in list_of_dicts:
if dict_card.has_key(x["CARD_NUMBER"]):
dict_card[x["CARD_NUMBER"]].append(x)
else:
dict_card[x["CARD_NUMBER"]] = x
This last bit of code is giving me an error:
Traceback (most recent call last):
File "<stdin>", line 3, in ?
AttributeError: 'dict' object has no attribute 'append'
I am having trouble locating my error. Being new to Python, I’m not entirely sure if the way in which I’m accessing list_of_dicts is correct.
This is caused because you are assigning just
xto the dict value, instead of[x], a list containing onlyx. You cannot append something to typex, only lists. To fix, changedict_card[x["CARD_NUMBER"]] = xtodict_card[x["CARD_NUMBER"]] = [x].Alternatively, just use