Reputation: 97
Evening all,
I'm attempting to add merge multiple lists into a dictionary. I've been able to access the spreadsheet, import the columns as lists and even assign valueA to the key. I'm struggling to append the valueB to the same key without overwriting the valueA.
My desired output is ('spreadsheet_key', ['valueA', 'valueB']) I can only achieve ('spreadsheet_key', ['valueB'])
There is clearly something that I don't understand about dictionaries. Any help would be greatly appreciated.
My code and comments are as follows:
import pandas as pd
df_xlsx = pd.read_excel("spreadsheet_name.xls") #assign a variable and access spreadsheet
# convert each column in spreadsheet into lists
spreadsheet_key = list(df_xlsx["Spreadsheet_Key"])
valueA = list(df_xlsx["valueA"])
valueB = list(df_xlsx["valueB"])
# merge two lists (spreadsheet_key and valueA) into a dictionary
dict1 = {} # create empty dictionary
for key in spreadsheet_key: # assigns spreadsheet_key as the key
for value in lithology: #assigns valueA as the value for the key
spreadsheet_key[key] = value # assigns key to value
valueA.remove(value)
break
print(dict1) #At this point I get the output of {spreadsheet_key: 'valueA'}
# my code fails after this point, while attempting to append valueB to spreadsheet_key
for key in spreadsheet_key: # assigns spreadsheet_key as the key
for value in valueB: #assigns valueB as the value for the key
spreadsheet_key[key] = value # assigns key to value
valueB.remove(value)
break
print(dict1) #result is that valueB overwrites valueA
Upvotes: 0
Views: 501
Reputation: 146
This error is occurring because you are overwriting the same key of the dictionary with another value rather than appending the value
You can achieve this with a single for loop
dict1 = {}
for key, value_a, value_b in zip(spreadsheet_key, valueA, valueB):
dict1[spreadsheet_key] = [value_a, value_b]
print(dict1)
Upvotes: 1