简体   繁体   English

如何在Python中结合字典格式的Excel文件和字典

[英]How to combine a dictionary formatted excel file with dictionary in Python

If I have an excel file that has no row/column labels that looks like this: 如果我有一个没有行/列标签的excel文件,看起来像这样:

在此处输入图片说明

and I have a dictionary that looks like this: 我有一本像这样的字典:

dict = {a:1, b:2, c:3}

How can I combine them into a dictionary that combines the values and that looks like this: 我如何将它们组合成一个字典,其中包含值,并且看起来像这样:

dict_result = {a:2, b:3, c:4}

Solution 1 解决方案1

If your excel file is in .xlsx format, you can use openpyxl : 如果您的excel文件为.xlsx格式,则可以使用openpyxl

import openpyxl

letter_map = {'a':1, 'b':2, 'c':3}

# open workbook
workbook = openpyxl.load_workbook('book1.xlsx')

# get worksheet by index
worksheet = workbook.worksheets[0]

result = {}

# loop over column pairs
for k, v in zip(worksheet['A'], worksheet['B']):

    # assign new values to keys
    result[k.internal_value] = v.internal_value + letter_map[k.internal_value]

print(result)

Output 产量

{'a': 2, 'b': 3, 'c': 4}

Solution 2 解决方案2

If you have your excel file in .xls format, you can use xlrd : 如果您具有.xls格式的excel文件,则可以使用xlrd

import xlrd

letter_map = {'a':1, 'b':2, 'c':3}

# open work book
workbook = xlrd.open_workbook('book1.xls', on_demand=True)

# get sheet by index
worksheet = workbook.sheet_by_index(0)

result = {}

# loop over row indices
for row in range(worksheet.nrows):

    # assign new values to keys
    k, v = worksheet.cell(row, 0).value, worksheet.cell(row, 1).value
    result[k] = int(v) + letter_map[k]

print(result)

Output 产量

{'a': 2, 'b': 3, 'c': 4}

This solution works for csv file having columns A and B 此解决方案适用于具有A and BA and B csv文件

import pandas as pd

actual_dict = {'a': 1, 'b': 1, 'c': 1}

cs = pd.read_csv(r'.\dict.csv')
keys = cs.A.tolist()
vals = cs.B.tolist()
csv_dict = {k:v for k,v in zip(keys,vals)}

for k in actual_dict.keys():
    actual_dict[k] += csv_dict[k] #updating the actual dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM