2016-02-24 75 views
-1

我創建了一個字典,其中一個鍵具有多個值 - start_time_C,duration_pre_val,value_T。所有這些都是從excel表輸入的。 然後我整理了字典。訪問字典python中第一個鍵的第三個值

pre_dict = {} 
pre_dict.setdefault(rows,[]).append(start_time_C) 
pre_dict.setdefault(rows,[]).append(duration_pre_val) 
pre_dict.setdefault(rows,[]).append(value_T) 
pre_dict_sorted = sorted(pre_dict.items(), key = operator.itemgetter(1)) 

現在,我想比較一個值(excel工作表的T列)與value_T。 如何從字典中訪問value_T?

非常感謝!

+0

這聽起來像你可能想使用numpy的結構性陣列或熊貓DataFrames這一點。 – Evert

回答

0

讓我們分成兩個部分是:

  1. 閱讀在電子表格

    I/O這樣的東西與pandas是最好的處理;如果您將使用Python中的電子表格和其他表格數據,熟悉這個軟件包。你可以做類似的數據

    import pandas as pd 
    
    #read the excel file into a pandas dataframe 
    my_data = pd.read_excel('/your/path/filename.xlsx', sheetname='Sheet1') 
    
  2. 訪問元素,創造一個字典現在

    您的電子表格的內容是大熊貓DataFrame「my_data」。在這裏,您可以參考數據框元素這樣

    #pandas: entire column 
    my_data['value_T'] 
    #pandas: 2nd row, 0th column 
    my_data.iloc[2, 0] 
    

    ,並創建Python數據結構

    #create a dict from the dataframe 
    my_dict = my_data.set_index(my_data.index).to_dict() 
    #access the values associated with the 'value_T key of the dict 
    my_dict['value_T'] 
    
+0

謝謝。但問題是我必須對字典中的數據進行排序然後進行比較。該列中的值由公式派生。所以我用openpyxl來獲取數據,操作它,然後將它附加到字典中。 – prj

相關問題