Skip to main content
 首页 » 编程设计

python之获取以索引为导向的嵌套字典中的键和值列表

2024年10月01日9Free-Thinker

我有一个结构如下的 Excel 文件:

name age status 
anna 35 single 
petr 27 married 

我已将这样的文件转换为具有如下结构的嵌套字典:

{'anna': {'age':35}, {'status': 'single'}}, 
{'petr': {'age':27}, {'status': 'married'}} 

使用 Pandas :

import pandas as pd 
df = pd.read_excel('path/to/file') 
df.set_index('name',  inplace=True) 
print(df.to_dict(orient='index')) 

但现在当运行 list(df.keys()) 时,它会返回字典中所有键的列表('age'、'status' 等),但不返回 'name'。

我的最终目标是通过输入名称返回所有键和值。

这有可能吗?或者也许我应该使用其他方式导入数据以实现目标?最终我还是应该找到一本字典,因为我会通过一个键将它与其他字典合并。

请您参考如下方法:

我想你需要参数 drop=False 到 set_index对于不删除列 Name:

import pandas as pd 
df = pd.read_excel('path/to/file') 
 
df.set_index('name',  inplace=True, drop=False) 
print (df) 
      name  age   status 
name                     
anna  anna   35   single 
petr  petr   27  married 
 
d = df.to_dict(orient='index') 
print (d) 
{'anna': {'age': 35, 'status': 'single', 'name': 'anna'},  
 'petr': {'age': 27, 'status': 'married', 'name': 'petr'}} 
 
print (list(df.keys())) 
['name', 'age', 'status']