繁体   English   中英

如何使用 python 将字典转换为字典列表

[英]How to convert dict to list of dict with python

如何转换这个字典

"Team":{
    "number": '2',
    "persons": ['Doe',"john"]
}

到这个字典列表

"Team" :[
    {"number": '2'},
   { "persons": ['Doe',"john"]}
]

我尝试了此链接中提到的解决方案,但对我没有任何作用。 提前致谢。

这可以通过列表理解来完成。

def convert(dictionary):
  return [{key: value} for key, value in dictionary.items()]

然后,你得到

>>> convert({"number": "2", "persons": ["Doe", "John"]})
[{"number": "2"}, {"persons": ["Doe", "John"]}]

你是说这样吗?

假设这是一个单一的字典

team_dict = {
    "number": '2',
    "persons": ['Doe',"john"]
}

new_team_dict = [{k: team_dict[k]} for k in team_dict ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM