I have a CSV file, call it csv_file. It has the following content:
Username, Password
name1, pass1
name2, pass2
...
I also have a dictionary, call it mydict
. It has the following content:
mydict = {
"name2" : "pass2",
"name3" : "pass3"
...
}
I want to update my CSV file to now include name3, pass3
, since those aren't in the CSV file but they are in the dictionary.
What's the most efficient, pythonic way of doing this?
Right now, here's what I have, but I don't think it's very efficient:
with open(csv_file, 'rb') as infile, open(new_csv_file, 'wb') as outfile:
r = csv.DictReader(infile)
w = csv.DictWriter(outfile, r.fieldnames)
w.writeheader()
temp_dict = {row['Username'] : row['Password'] for row in r}
for k in mydict:
if k.key not in temp_dict:
temp_dict[k] = mydict[k]
for value in temp_dict:
w.writerow({'Username' : value, 'Password' : temp_dict[value]})
I'm sure there's something I can do to make this better. Any suggestions?
new_csv_file
or I can replace the old one. But I haven't decided what I'll do at that point yet. \$\endgroup\$mydict
but not update the password of any existing ones? \$\endgroup\$