Reputation: 131
I am trying to create a dictionary from two columns in MySQL database. in my first attempt I have extracted two list and zipped them together to create a python dictionary.
As I thought lists kept their order, I assumed the two lists would match in terms of order and the url would relate to the specific player in the dictionary, but this doesn't seem to be the case
My code is:
#extract a player list from db
cur.execute("SELECT full_name FROM player")
player_names_two = cur.fetchall()
player_name_list_two = [row[0] for row in player_names] #convert to list
#exctract url list from same table in db
cur.execute("SELECT real_gm_profile FROM player")
profile_urls = cur.fetchall()
profile_urls_list = [row[0] for row in profile_urls]
#player and url dict
team_player_dic = dict(zip(player_name_list_two, profile_urls_list))
I then want to use the dictionary to check details and update my database, which is all working ok, albeit the urls do not match the player so updating incorrectly at the moment.
Is there a better way to do this to ensure the key, values match correctly?
Thank you
Upvotes: 1
Views: 1235
Reputation: 82765
Fetch full_name
& real_gm_profile
in a single query and then use a dict comprehension
Ex:
#extract a player list from db
cur.execute("SELECT full_name, real_gm_profile FROM player")
result_set = cur.fetchall()
team_player_dic = {row["full_name"]: row['real_gm_profile'] for row in result_set} # OR {row[0]: row[1] for row in result_set}
Upvotes: 1