【发布时间】:2011-10-17 13:30:07
【问题描述】:
我有一个存储 URL 的字典列表。它只有两个字段,title 和 url。示例:
[
{'title': 'Index Page', 'url': 'http://www.example.com/something/index.htm'},
{'title': 'Other Page', 'url': 'http://www.example.com/something/other.htm'},
{'title': 'About Page', 'url': 'http://www.example.com/thatthing/about.htm'},
{'title': 'Detail Page', 'url': 'http://www.example.com/something/thisthing/detail.htm'},
]
但是,我想从这个字典列表中得到一个树结构。我正在寻找这样的东西:
{ 'www.example.com':
[
{ 'something':
[
{ 'thisthing':
[
{ 'title': 'Detail Page', 'url': 'detail.htm'}
]
},
[
{ 'title': 'Index Page', 'url': 'index.htm'},
{ 'title': 'Other Page', 'url': 'other.htm'}
]
]
},
{ 'thatthing':
[
{ 'title': 'About Page', 'url': 'about.htm'}
]
}
]
}
我的第一次尝试是在一堆 for 循环中使用 urlparse 汤,我相信有更好更快的方法来做到这一点。
我看到人们在 SO 上使用列表推导、lambda 函数等来发挥神奇的作用。我仍在弄清楚它的过程中。
(对于 Django 开发人员:我将使用这个我的 Django 应用程序。我将 URL 存储在一个名为 Page 的模型中,该模型有两个字段 name 和 title)
【问题讨论】:
标签: python