如何将python字典转换为所需格式

Shobi

我有以下字典,当to_dict()在pandas数据框上应用方法时得到了该字典

{
   'name' : {
      0: 'abc',
      1: 'xyz'
    },
   'email': {
     0: '[email protected]',
     1: '[email protected]',
   },
   'category': {
     0: 'category 1',
     1: 'category 2', 
   }
}

如何将其转换为以下结构?

[
  {
    'name': 'abc',
    'email' : '[email protected]',
    'category': 'category 1',  
  },
  {
    'name': 'xyz',
    'email' : '[email protected]',
    'category': 'category 2',  
  }
]

我尝试应用多种for循环形式,但都是伪代码,如果有人可以帮助或指向某些链接,那太好了,这里的python newbie:|

编辑:将所需的结构更改为字典列表,因为字典不是哈希表,

诺斯克洛

您显示的目标结构是一组字典。由于字典不可散列,因此无法创建。

相反,您可能想要一份字典列表。

result = [
     {k: yourdict[k][n] for k in yourdict} for n in sorted(yourdict['name'])
]

测试:

[
    {'category': 'category 1', 'email': '[email protected]', 'name': 'abc'},
    {'category': 'category 2', 'email': '[email protected]', 'name': 'xyz'}
]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章