如何转换此字典结构
[
{ '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'}
]
对不起,通用标题。也许我只是错过了正确的术语。
我可以尝试循环播放这些项目。一个内置的函数或库会很好。
答案 0 :(得分:1)
迭代街道上的所有项目并与城市结合
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'}]