如何通过Pandas将列表列表型字典转换为字典型字典?
基于Pandas列遍历的字典格式转换
给定初始字典a,需要将其转换为b的目标格式:
import pandas as pd a = {'01AB': [["ABC",5],["XYZ",4],["LMN",1]], '02AB_QTY': [["Other",20],["not_Other",150],["another",15]]} # 期望的目标格式 b = {'01AB': {"ABC":5,"XYZ":4,"LMN":1}, '02AB_QTY': {"Other":20,"not_Other":150,"another":15}}
直接使用pd.DataFrame(a).to_dict(orient='dict')得到的结果不符合预期,会生成以索引为键的嵌套结构:
{'01AB': {0: ['ABC', 5], 1: ['XYZ', 4], 2: ['LMN', 1]}, '02AB_QTY': {0: ['Other', 20], 1: ['not_Other', 150], 2: ['another', 15]}}
解决方案:仅遍历Pandas DataFrame列实现转换
通过遍历DataFrame的每一列,将列内的键值对列表直接转换为字典即可:
import pandas as pd a = {'01AB': [["ABC",5],["XYZ",4],["LMN",1]], '02AB_QTY': [["Other",20],["not_Other",150],["another",15]]} df = pd.DataFrame(a) b = {} # 遍历DataFrame的列 for col in df.columns: # 将列中每个[key, value]子列表组成的序列转为字典 b[col] = dict(df[col].tolist()) print(b) # 输出结果: # {'01AB': {'ABC': 5, 'XYZ': 4, 'LMN': 1}, '02AB_QTY': {'Other': 20, 'not_Other': 150, 'another': 15}}
原理说明
df[col].tolist()会将当前列的所有元素(即每个[key, value]子列表)提取为一个列表序列;- Python内置的
dict()函数可以直接接收这种键值对序列,将其转换为对应的字典结构。
内容的提问来源于stack exchange,提问作者NNM
相关产品推荐
相关产品推荐

