[Tutor] how-to generate specific lines of text from two python lists
Mats Wichmann
mats at wichmann.us
Mon Jun 26 13:18:36 EDT 2017
On 06/25/2017 12:44 PM, Tahir Hafiz wrote:
> Thanks Alan and Peter,
>
> Alan you are right this could be solved via an SQL statement but I was
> asked to finish the python script.
> Anyways, this worked and helped to solve the problem in the end:
>
> # Create iterator object, dictionary which can be used to iterate against.
> b_iter = iter(new_emails)
>
>
> print "Creating a list of usernames and email addresses from retreived
> database data:"
> if __name__ == "__main__":
> dictionary = dict(zip(usernames, new_emails))
> my_list = []
> for username in usernames:
>
> my_list.append({'username':username, 'email':next(b_iter)})
>
> print my_list
>
> print
> print "Creating a file called update_emails.sql with UPDATE statements from
> the list."
> # Open a file in write mode and write the UPDATE sql statements to the file
> # Close the file once iterated against.
> with open('update_emails.sql', 'w') as f:
> for i in my_list:
> mystring = "UPDATE users set email='{0}' WHERE username='{1}';"
> new_mystring = mystring.format(i['email'], i['username'])
> f.write(new_mystring + '\n')
> f.close()
I'd like to point out that with this solution you are creating a
dictionary named "dictionary" but then never using it, and you then
proceed to make a list consisting of dictionaries which each look like a
single record. Far be it from me to tell you this is wrong since you
report the effort is working out!!! But you do seem to be redoing work.
Consider this as a simplified alternative, which actually uses the
dictionary you create up front (ignoring the very valid "don't do it
this way" comments you have already received, let the database connector
handle the quoting). Also note you don't need to "close the file once
iterated against", since that's the exact purpose of the 'with'
statement - to handle that cleanup for you.
print "Creating dictionary of usernames and email addresses from
retreived database data:"
if __name__ == "__main__":
dictionary = dict(zip(usernames, new_emails))
print dictionary
print
print "Creating a file called update_emails.sql with UPDATE
statements from the list."
# Open a file in write mode and write the UPDATE sql statements to
the file
with open('update_emails.sql', 'w') as f:
for key in dictionary.keys():
mystring = "UPDATE users set email='{0}' WHERE username='{1}';"
new_mystring = mystring.format(dictionary[key], key)
f.write(new_mystring + '\n')
More information about the Tutor
mailing list