[英]Getting a nested dictionary from excel table in Python
我有一個像這樣的excel數據:
Dep request date Code Reason
P41 15.02.2018 0060 Data Incomplete
P41 02.02.2018 0060 Data Incomplete
P21 11.01.2018 0060 Data Incomplete
P41 14.02.2018 0060 Data Incomplete
P01 13.03.2018 0060 Data Incomplete
P21 09.02.2018 0030 Typing error -> technical mix-up
P41 07.02.2018 0030 Typing error -> technical mix-up
P31 28.02.2018 0030 Typing error -> technical mix-up
這是我的代碼:
def get_reasons(readfilename):
act_sheet = read_excelfile(readfilename)
deps = []
reasons = []
item_dict = {}
# create a list of uppercase letters for A-Z
col_header = [chr(one).upper() for one in range(97,123)]
for idx, header in enumerate(col_header):
head = header + str(1)
if act_sheet[head].value == 'Dep':
for j in range(2, act_sheet.max_row+1):
deps.append(act_sheet[header + str(j)].value)
if act_sheet[head].value == 'Reason':
for m in range(2, act_sheet.max_row+1):
items = act_sheet[header + str(m)].value
reasons.append(items)
item_dict.setdefault(items, {})
item_dict[items].setdefault('Departments', deps)
amounts = Counter(reasons)
for k,v in amounts.items():
item_dict[k]['Quantity'] = v
return item_dict
我正在嘗試以這種格式返回字典:
{u'Data Incomplete': {'Departments': [P41, P41, P21, P41, P01], 'Quantity': 1},
u'Typing error -> technical mix-up': {'Department': [P21, P41, P31], 'Quantity': 1}}
我正在努力獲取正確的代碼,尤其是獲取部門清單的那一部分。 有人可以幫我嗎?
最好的方法是使用數據庫。 但是,一次性使用openpyxl非常容易。 您實際上應該更仔細地研究文檔中的示例,以使您不必像現在那樣編寫冗長的代碼,這使得很難准確地理解您要執行的操作。
以下內容將幫助您。
headers = {c.value:c.col_idx for c in ws[1]}
reason_col = headers['Reason'] - 1
dep_col = headers['Dep'] - 1
reasons = defaultdict(set)
for row in ws.iter_rows(min_row=2):
reason = row[reason_col].value
dep = row[dep_col].value
reasons[reason].add(dep)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.