首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python中对嵌套字典进行排序?

如何在python中对嵌套字典进行排序?
EN

Stack Overflow用户
提问于 2015-05-13 09:49:10
回答 1查看 189关注 0票数 0

我在我的项目中有一个嵌套字典:

代码语言:javascript
复制
>>> 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
                }
            ]
        }
    ]
}

以及生成它的函数:

代码语言:javascript
复制
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}

问题是,它作为后代返回一组无序字典:

在我的情况下,当它们被嵌套时,如何排序?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-13 09:54:12

您的descendent值只是一个列表。列表可以排序,无论它们被引用在哪里。它在字典里并不重要。

您的descendent列表顺序由os.listdir()返回的任何顺序设置。您可以对此进行排序,也可以简单地对descendent对象本身进行排序。例如,使用natural sort进行排序,或者使用任何其他条件进行排序。

例如,在natural_sort()结果上使用来自Mark Byer's answeros.listdir()函数:

代码语言:javascript
复制
for entry in natural_sort(os.listdir(dirpath)):

按排序顺序列出目录条目,以便插入到descendant列表中。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30211248

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档