DictWriter just doesn’t seem to be working for me.
Current code:
myfile = open('hashdict.csv', 'wb')
fieldnames = ('md5', 'value')
myWriter = csv.DictWriter(myfile, fieldnames=fieldnames)
headers = dict((n,n) for n in fieldnames)
myWriter.writerow(headers)
for n in dictToSearch:
myWriter.writerow(n)
myfile.close()
Traceback:
Traceback (most recent call last):
File "hash.py", line 42, in <module>
myWriter.writerow(n)
File "C:\Python27\lib\csv.py", line 148, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "C:\Python27\lib\csv.py", line 144, in _dict_to_list
", ".join(wrong_fields))
ValueError: dict contains fields not in fieldnames: d, 1, a, 5, 0, d, 0, a, 1, 7
, 0, e, 5, e, a, 9, f, e, b, 6, f, 7, 9, 6, 1, 3, 6, 3, f, 6, d, 9
The alphanumerical characters are from an MD5 hash, but that’s about all I can tell you. I’ve looked at the documentation and can’t seem to make sense of it. What I’m trying to do is make a CSV file out of the dictionary called dictToSearch.
Thanks in advance for any help, and let me know if you need any other information.
Link to full code: http://pastebin.com/A3E4AJfV
The key missing piece of information here: what is dictToSearch? I guess that it’s something like {‘e2fc714c4727ee9395f324cd2e7f331f’: ‘abcd’, ‘098f6bcd4621d373cade4e832627b4f6’: ‘test’}.
If so, the issue here is that “for n in dictToSearch” sets n to the first key of dictToSearch – which will be an MD5 hash. writerow(n) then interprets that MD5 hash string as a dictionary in its own right consisting of single-character keys and values, not as a string.
I suspect that what you really want to do is:
which converts an entry from dictToSearch into its own dictionary matching the field names you’re using.