简体   繁体   English

将嵌套的字典列表转换为平面的字典列表

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

How do I convert this dictionary structure如何转换此字典结构

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

into this one?进入这个?

[
    { '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'}
]

Sorry for the generic title.对不起,通用标题。 Perhaps I'm just missing the correct term.也许我只是错过了正确的术语。

I could try to loop of the items.我可以尝试循环这些项目。 A built in function or library for that would be nice.内置的 function 或库会很好。

iterate all the items in street and combine with city迭代街道中的所有项目并与城市结合

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