【发布时间】:2020-07-16 23:49:22
【问题描述】:
晚上好,
我正在尝试将多个列表合并到字典中。我已经能够访问电子表格,将列作为列表导入,甚至将 valueA 分配给键。我正在努力将 valueB 附加到同一个键而不覆盖 valueA。
我想要的输出是 ('spreadsheet_key', ['valueA', 'valueB']) 我只能实现('spreadsheet_key', ['valueB'])
显然我对字典有些不理解。任何帮助将不胜感激。
我的代码和cmets如下:
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
【问题讨论】:
标签: python list dictionary merge