简体   繁体   English

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

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

How to convert this dict如何转换这个字典

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

to this list of dict到这个字典列表

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

I tried the solutions mentioned in this link but nothing works for me.我尝试了此链接中提到的解决方案,但对我没有任何作用。 Thanks in advance.提前致谢。

That can be done by list comprehension.这可以通过列表理解来完成。

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

Then, you get然后,你得到

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

Do you mean like this?你是说这样吗?

let's say it's a single dict假设这是一个单一的字典

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