您知道是否有一種快速的方法可以進行以下字典轉換?(不回圈通過dict的鍵并從頭開始構建它)
從這個嵌套的 python 字典中:
{
"demographicAll": {
"allAges": {
"rating": "8.8",
"votes": "2327099"
},
"agesUnder18": {
"rating": "9.0",
"votes": "1050"
},
"ages18To29": {
"rating": "9.0",
"votes": "363089"
},
"ages30To44": {
"rating": "8.8",
"votes": "914737"
},
"agesOver45": {
"rating": "8.2",
"votes": "182612"
}
}
}
對此:
{
"demographicAll": [
{
"ageRange": "allAges",
"rating": "8.8",
"votes": "2327099"
},{
"ageRange": "agesUnder18",
"rating": "9.0",
"votes": "1050"
},{
"ageRange": "ages18To29",
"rating": "9.0",
"votes": "363089"
},{
"ageRange": "ages30To44",
"rating": "8.8",
"votes": "914737"
},{
"ageRange": "agesOver45",
"rating": "8.2",
"votes": "182612"
}
]
}
uj5u.com熱心網友回復:
我能做的最好的(它仍然回圈通過串列理解中的字典)是:
mydict = {
"demographicAll": {
"allAges": {
"rating": "8.8",
"votes": "2327099"
},
"agesUnder18": {
"rating": "9.0",
"votes": "1050"
},
"ages18To29": {
"rating": "9.0",
"votes": "363089"
},
"ages30To44": {
"rating": "8.8",
"votes": "914737"
},
"agesOver45": {
"rating": "8.2",
"votes": "182612"
}
}
}
d = mydict["demographicAll"]
mydict["demographicAll"] = [d[key] for key in d if not d[key].update({'ageRange':key})]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/526847.html
下一篇:練習排序字典
