簡體   English   中英

如何在python中對嵌套字典進行排序?

[英]How to sort nested dictionary in python?

我的項目中有一個嵌套的字典:

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

問題是它返回無序的字典集作為后代:

在此處輸入圖片說明

在我嵌套的情況下,如何對它們進行排序?

您的descendent只是一個列表 列表可以排序,無論引用在何處。 它在字典中並不重要。

您的descendent列表順序由os.listdir()返回的順序設置。 您可以對其進行排序,也可以descendent對象本身進行排序。 例如,使用自然排序進行排序 ,或者使用任何其他條件進行排序。

os.listdir()結果上使用Mark Byer的答案中natural_sort()函數,例如:

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

會以排序順序列出您的目錄條目,以便您插入descendant列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM