我在我的项目中有一个嵌套字典:
>>> dict = {
"content": """<p>It is common for content in Arabic, Hebrew, and other languages that use right-to-left scripts to include numerals or include text from other scripts. Both of these typically flow left-to-right within the overall right-to-left context. </p>""",
"name": "directory",
"decendent": [
{
"content": """<p>This article tells you how to write HTML where text with different writing directions is mixed <em>within a paragraph or other HTML block</em> (ie. <dfn id="term_inline">inline or phrasal</dfn> content). (A companion article <a href="/International/questions/qa-html-dir"><cite>Structural markup and right-to-left text in HTML</cite></a> tells you how to use HTML markup for elements such as <code class="kw">html</code>, and structural markup such as <code class="kw">p</code> or <code class="kw">div</code> and forms.)</p>""",
"name": "subdirectory",
"decendent": None
},
{
"content": """It tells you how to use HTML markup for elements such as <code class="kw">html</code>, and structural markup such as <code class="kw">p</code> or <code class="kw">div</code> and forms.)""",
"name": "subdirectory_two",
"decendent": [
{
"content": "Name 4",
"name": "subsubdirectory",
"decendent": None
}
]
}
]
}以及生成它的函数:
def getname(dirpath):
onlyfile = [entry for entry in os.listdir(dirpath) if os.path.isfile(os.path.join(dirpath, entry)) and entry.endswith(".txt")][0]
onlyfilename = os.path.join(dirpath, onlyfile)
decendent = []
for entry in os.listdir(dirpath):
entrypath = os.path.join(dirpath, entry)
if os.path.isfile(entrypath):
continue
decendent.append(getname(entrypath))
if len(decendent) == 0:
decendent = None
return {'name': onlyfilename.split("/")[-2],
'path': onlyfilename.rsplit("/", 1)[-2] + "/index.html",
'leaf': readFile(onlyfilename),
'decendent': decendent}问题是,它作为后代返回一组无序字典:

在我的情况下,当它们被嵌套时,如何排序?
发布于 2015-05-13 09:54:12
您的descendent值只是一个列表。列表可以排序,无论它们被引用在哪里。它在字典里并不重要。
您的descendent列表顺序由os.listdir()返回的任何顺序设置。您可以对此进行排序,也可以简单地对descendent对象本身进行排序。例如,使用natural sort进行排序,或者使用任何其他条件进行排序。
例如,在natural_sort()结果上使用来自Mark Byer's answer的os.listdir()函数:
for entry in natural_sort(os.listdir(dirpath)):按排序顺序列出目录条目,以便插入到descendant列表中。
https://stackoverflow.com/questions/30211248
复制相似问题