簡體   English   中英

如何grep列並將其添加到字典鍵中作為值

[英]How to grep a column and add it in dictionary key as value

我一直在excel中工作,我正在嘗試獲取包含鍵和值的字典。這是我的表:

int1           int2         int3    int4         int5

core_6  2       22           32     core_8      23.34.34.45

72.20.20.20     11           33     core_7      core_work

255.255.255.0   12           12     core_12     44      

我試圖做為:

{'int1' : 'core_6' '72.20.20.20' ,'255.255.255.0' 'int2': and so on}.

我的代碼面臨的問題是:

import xlrd

workbook = xlrd.open_workbook('input.xlsx')
workbook = xlrd.open_workbook('input.xlsx', on_demand = True)
worksheet = workbook.sheet_by_name("GlobalInfo")

my_dict = {}
for i in range(2):
    row = worksheet.row_values(i)
    my_dict[row[1]] = row[1::]

d =dict((k, v) for k,v in my_dict.items() if k is not None and k != '')

for x in d:
    print(d[x])

my_di = {k: '' for k in d[x]} 
print(my_di)  ////take all the int1 as keys
worksheet.cell_value(0, 1) 
num_rows = worksheet.nrows - 1
curr_row = 1
kk = []

while curr_row < num_rows:
        curr_row += 1
        row = worksheet.row(curr_row)
        kk.append(row[1].value)

print(kk)     ///this will print value of 1st row

但是我無法為我制作的鍵添加值。

我也無法獲取其他行的值。

黑客解決方案,分步進行:

1)將Excel文件另存為.csv文件到“ myfile.csv”

2)

import pandas as pd
df = pd.read_csv('myfile.csv')

3)現在可以像處理字典一樣處理pandas數據框,例如,可以調用df['int1']打印關聯的列

使用openpyxl嘗試這種方法:

from openpyxl import load_workbook

#load file
wb = load_workbook(filename='input.xlsx', read_only=True)
# select sheet
ws = wb["GlobalInfo"]

data = {}
# build data dict, using column index as dict key saving header title
for idx, header in enumerate(list(ws.rows)[0]):
    data[idx] = {"title": header.value, "items": []}

# put each cell value
for row in list(ws.rows)[1:]:
    for idx, cell in enumerate(row):
        data[idx]["items"].append(cell.value)

# set header titles as dict keys 
data = dict([(y["title"], y["items"] ) for x, y in data.items()])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM