简体   繁体   English

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

[英]How to sort nested dictionary in python?

I have a nested dictionary in my project: 我的项目中有一个嵌套的字典:

>>> 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
                }
            ]
        }
    ]
}

and a function which generates it: 和一个生成它的函数:

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}

The problem is that it returns an unordered set of dictionaries as descendents: 问题是它返回无序的字典集作为后代:

在此处输入图片说明

How to sort them in my case when they're nested? 在我嵌套的情况下,如何对它们进行排序?

Your descendent value is just a list . 您的descendent只是一个列表 Lists can be sorted, no matter where they are referenced. 列表可以排序,无论引用在何处。 That it is inside a dictionary doesn't matter here. 它在字典中并不重要。

Your descendent list order is set by whatever order os.listdir() returns. 您的descendent列表顺序由os.listdir()返回的顺序设置。 You can sort that, or you can simply sort the descendent object itself. 您可以对其进行排序,也可以descendent对象本身进行排序。 Sort by using a natural sort for example, or use any other criteria for your sorting. 例如,使用自然排序进行排序 ,或者使用任何其他条件进行排序。

Using the natural_sort() function from Mark Byer's answer on the os.listdir() result, for example: os.listdir()结果上使用Mark Byer的答案中natural_sort()函数,例如:

for entry in natural_sort(os.listdir(dirpath)):

would list your directory entries in a sorted order for you to insert into the descendant list. 会以排序顺序列出您的目录条目,以便您插入descendant列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM