[英]Creating Python Dictionary from excel
我想根據從excel文件導入的值創建字典,我的代碼如下:
import xlrd
file_location = "data.xlsx"
workbook = xlrd.open_workbook(file_location)
M_Sheet = workbook.sheet_by_name("MM")
D_Sheet = workbook.sheet_by_name("DD")
F_sheet = workbook.sheet_by_name("FF")
M = []
for i in range(M_Sheet.nrows):
value = (M_Sheet.cell(i,0).value)
M.append(value)
D = []
for j in range(D_Sheet.nrows):
value = (D_Sheet.cell(j,0).value)
D.append(value)
F = []
for f in range(F_Sheet.nrows):
value = (F_Sheet.cell(f,0).value)
F.append(value)
我想創建一個字典,如DICT,它包含來自excel文件的值,而
M=['s1', 's2',… 'si']
,
D=['d1', 'd2',….. 'dj']
和
F=[ c1, c2, … cf]
是從excel文件構建的。
對於M,D和F的2個值:
DICT={'s1': {'d1': c1, 'd2': c2}, 's2': {'d1': c3, 'd2': c4}}
關於如何創建此字典(DICT)的任何想法嗎?
如果我了解您的邏輯,請參閱以下解決方案:
#method to create samples list
nb_s = 3;nb_d = 2
S = ['s' + str(x) for x in range(1, nb_s + 1)]
D = ['d' + str(x) for x in range(1, nb_d + 1)]
C = ['c' + str(x) for x in range(1, (len(S) * len(D)) + 1)]
print(S);print(D);print(C)
dico_s = {}
for s in S:
dico_d = {}
for d in D:
idx = D.index(d) + len(D) * S.index(s)
dico_d[d] = C[idx]
dico_s[s] = dico_d
print(dico_s)
輸出:
S ->['s1', 's2', 's3']
D ->['d1', 'd2']
C->['c1', 'c2', 'c3', 'c4', 'c5', 'c6']
DICO->{'s1': {'d1': 'c1', 'd2': 'c2'},
's2': {'d1': 'c3', 'd2': 'c4'},
's3': {'d1': 'c5', 'd2': 'c6'}}
--------------------------
**for nb_s = 4 and nb_d = 6**
S -> ['s1', 's2', 's3', 's4']
D -> ['d1', 'd2', 'd3', 'd4', 'd5', 'd6']
C -> ['c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10', 'c11', 'c12',
'c13', 'c14', 'c15', 'c16', 'c17', 'c18', 'c19', 'c20', 'c21', 'c22', 'c23', 'c24']
DICO -> {'s1': {'d1': 'c1', 'd2': 'c2', 'd3': 'c3', 'd4': 'c4', 'd5': 'c5', 'd6': 'c6'},
's2': {'d1': 'c7', 'd2': 'c8', 'd3': 'c9', 'd4': 'c10', 'd5': 'c11', 'd6': 'c12'},
's3': {'d1': 'c13', 'd2': 'c14', 'd3': 'c15', 'd4': 'c16', 'd5': 'c17', 'd6': 'c18'},
's4': {'d1': 'c19', 'd2': 'c20', 'd3': 'c21', 'd4': 'c22', 'd5': 'c23', 'd6': 'c24'}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.