簡體   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