【发布时间】:2021-11-01 05:30:56
【问题描述】:
我认为这个问题与本论坛之前的问题类似。但是,我仍然对如何从元组列表创建嵌套字典有疑问。
假设我有以下元组:
my_list = [
('actor', 'actor_id', 'integer', 'NO'),
('actor', 'first_name', 'character varying', 'NO'),
('actor_info', 'actor_id', 'integer', 'YES'),
('actor_info', 'first_name', 'character varying', 'YES')]
# convert into DataFrame
col = ['table', 'col_name', 'dtype', 'isnull']
df = pd.DataFrame(mylist, columns=col)
print(df)
table col_name dtype isnull
0 actor actor_id integer NO
1 actor first_name character varying NO
2 actor_info actor_id integer YES
3 actor_info first_name character varying YES
当前结果:
{
'actor': {
'actor_id': {'dtype': 'integer', 'isnull': 'NO'},
'first_name': {'dtype': 'character varying', 'isnull': 'NO'}
},
'actor_info': {
'actor_id': {'dtype': 'integer', 'isnull': 'YES'},
'first_name': {'dtype': 'character varying', 'isnull': 'YES'}
}
}
预期结果(应按表名分组):
{
'actor':
[
{'column': 'actor_id', 'dtype': 'integer', 'isnull': 'NO'},
{'column': 'first_name', 'dtype': 'character varying', 'isnull': 'NO'}
],
'actor_info':
[
{'column': 'actor_id', 'dtype': 'integer', 'isnull': 'YES'},
{'column': 'first_name', 'dtype': 'character varying', 'isnull': 'YES'}
]
}
我尝试通过将 my_list 转换为 DataFrame 来制作嵌套字典。但是,我无法获得所需的输出结果。这是我的当前代码:
# convert to nested dictionary
ff = df.iloc.groupby(['table'])[['col_name','dtype','isnull']].apply(lambda x: x.set_index('col_name').to_dict(orient='index')).to_dict()
# convert to JSON
print(json.dumps(ff, indent=1))
你能帮我解决这种问题吗?
我也很好奇如何不转换为DataFrame(例如,列表理解、嵌套循环)来解决这个问题。任何有助于解决此问题的帮助将不胜感激。谢谢
【问题讨论】:
-
你的输出不清楚,你的意思是应该是
table_name -> list of dicts吗?因为显然,您不能在 dict (column) 中有重复键。其次,除非您真的打算使用pandas进行进一步操作,否则绝对应该坚持使用纯 Python。似乎有点矫枉过正。 -
@kva1966 哦,对不起。感谢您的指正和建议。我已经编辑了我的问题(预期结果)。
-
没问题。只是还是有点好奇,要一份清单吗?因为如果您使用大括号 (
{}),这意味着字典(在您当前的编辑中)。如果您希望列元数据位于列表中,则应为[ ... ](方括号)。很抱歉吹毛求疵,只是您的预期输出仍然不太正确,将其放入 Ipython 或类似文件中,它会出错,因为字典必须是键值对,所以您有{ val1, val2 }。 -
@kva1966 啊,我明白了。是的,我只想返回每列的列元数据。实际上,我在设计输出时有点困惑,我应该将
[]或{}作为输出。谢天谢地,你给了我解释。谢谢。
标签: python pandas dictionary