繁体   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