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野路子】

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容