簡體   English   中英

將嵌套的字典列表轉換為平面的字典列表

[英]Convert nested list of dicts to flat list of dicts

如何轉換此字典結構

[
    { 'city': 'Fake City', 'streets': {'Fake Street', 'Fake Way'}},
    { 'city': 'Ocean City', 'streets': {'Ocean Street', 'Ocean Way'}},
    { 'city': 'Forest City', 'streets': {'Forest Street', 'Forest Way'}},
]

進入這個?

[
    { 'city': 'Fake City', 'street': 'Fake Street'},
    { 'city': 'Fake City', 'street': 'Fake Way'},
    { 'city': 'Ocean City', 'street': 'Ocean Street'},
    { 'city': 'Ocean City', 'street': 'Ocean Way'},
    { 'city': 'Forest City', 'street': 'Forest Street'},
    { 'city': 'Forest City', 'street': 'Forest Way'}
]

對不起,通用標題。 也許我只是錯過了正確的術語。

我可以嘗試循環這些項目。 內置的 function 或庫會很好。

迭代街道中的所有項目並與城市結合

a = [
        { 'city': 'Fake City', 'streets': {'Fake Street', 'Fake Way'}},
        { 'city': 'Ocean City', 'streets': {'Ocean Street', 'Ocean Way'}},
        { 'city': 'Forest City', 'streets': {'Forest Street', 'Forest Way'}},
    ]

res = []
for item in a:
    for st in item["streets"]:
        res.append({"city": item["city"], "streets": st})

res


[{'city': 'Fake City', 'streets': 'Fake Street'},
 {'city': 'Fake City', 'streets': 'Fake Way'},
 {'city': 'Ocean City', 'streets': 'Ocean Street'},
 {'city': 'Ocean City', 'streets': 'Ocean Way'},
 {'city': 'Forest City', 'streets': 'Forest Way'},
 {'city': 'Forest City', 'streets': 'Forest Street'}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM