Brian Breeden
Brian Breeden

Reputation: 101

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:

enter image description here

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}

Upvotes: 2

Views: 709

Answers (2)

letmecheck
letmecheck

Reputation: 1369

This solution works for csv file having columns A and B

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

Upvotes: 0

RoadRunner
RoadRunner

Reputation: 26315

Solution 1

If your excel file is in .xlsx format, you can use 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

If you have your excel file in .xls format, you can use 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}

Upvotes: 2

Related Questions