简体   繁体   中英

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 ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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