Reputation: 57
I am developing a python script to analyse a txt file and then save it to a osv file. I am trying to use "zip_longest" from the module "itertools". When one of my dictionaries no longer has i value i want it to paste a empty space while the other dictionary continues to paste its values. My code looks like this:
def csvExport(self):
exportYN = input("Would you like to export the document to a CSV file? (Y/N):")
if (exportYN == "Y" or exportYN == "y"):
with open('data.csv', 'w', encoding="utf-8") as csvfile:
csvfile.write("Username;Repeated;Password;Repeated")
for (username, usrValue), (password, passValue) in itertools.zip_longest(self.usernames.items(), self.passwords.items()):
csvfile.write(str(username) + ";" + str(usrValue) + ";" + str(password) + ";" + str(passValue))
And the error code looks like this:
for (username, usrValue), (password, passValue) in itertools.zip_longest(self.usernames.items(), self.passwords.items()):
TypeError: 'NoneType' object is not iterable
I think it is related to zip_longest because the two dictionaries i use is not the same length.
Hope you can help :)
Upvotes: 2
Views: 904
Reputation: 16988
You need to use the fillvalue
keyword argument of zip_longest
:
ziplongest(..., ..., fillvalue=('', ''))
Otherwise the default is None
and None
cannot fill a 2-tuple for example (username, usrValue)
.
Aside from that, since dictionaries are not ordered the zip
operation will return random pairs...
Upvotes: 2