pandas將一行數據轉換為字典

需求:將兩列轉換為字典形式


image.png
import pandas as pd
import json
from pathlib import Path


def excel_to_dict():
    #BASE_DIR = Path(__file__).resolve(strict=True).parent.parent

    print('path=', __file__)
    print('path=', Path(__file__).resolve(strict=True).parent)
    file_dir = Path(__file__).resolve(strict=True).parent
    # 
    df = pd.read_excel(file_dir / '航線映射表.xlsx', engine='openpyxl')
    
    data_dict =  {key:values for key, values in zip(df['鍵'], df['值'])}

    print(len(data_dict))

    with open(file_dir / 'test.json', 'w') as f:
        json.dump(data_dict, f)

結果:


image.png

更多學習筆記整理于微信公號【Python野路子】

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容