【问题标题】:Assign multiple values to a key from Excel (Python Dictonaries)将多个值分配给 Excel(Python 字典)中的键
【发布时间】: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


    【解决方案1】:

    发生此错误是因为您正在用另一个值覆盖字典的相同键而不是附加值

    您可以通过单个for loop 实现此目的

    dict1 = {}
    for key, value_a, value_b in zip(spreadsheet_key, valueA, valueB):
        dict1[spreadsheet_key] = [value_a, value_b]
    
    print(dict1)
    

    【讨论】:

    • 啊,这看起来整洁多了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 2021-12-27
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多