按字母顺序排列字典(Python) [英] Sorting a dictionary both hierarchically and alphabetically (Python)

查看:831
本文介绍了按字母顺序排列字典(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python字典(product_dict)来表示产品及其所有子部件的层次结构。 dict的密钥是唯一的ID(UUID),值是包含有关这些部分的所有信息的Class对象,包括:

  .name#包含组件实际名称的字符串
part.idCode#组件的UUID
part.parent#父组件的UUID
part.children#子组件的UUID列表
part.tier#一个整数,指定层次结构中的层/级别

现在以有序的方式输出数据的目的,我希望对这些部分进行分层和字母排序。对于使用树结构的层次排序,我发现这个问题的答案非常适合打印:分层次数据排序。对于这个例子来处理我的数据结构,我做了一些修改:

  class Node:
def __init__ (self,article):
self.article = article
self.children = []
self.parent =无
self.name =无

def printer(self,level = 0):
print('{} {}'。format('\t'* level,self.name))
for child for self.children:
child.printer(level + 1)


class Tree:
def __init __(self):
self.nodes = {}

def push(self,article,parent,name):
如果父级不在self.nodes中:
self.nodes [parent] = Node(parent)
如果文章不在self.nodes中:
self.nodes [article] = Node(article)
如果parent == article:
return
self.nodes [article] .name = name
se lf.nodes [article] .parent = self.nodes [parent]
self.nodes [parent] .children.append(self.nodes [article])

@property
def roots(self):
return(x for x in self.nodes.values()if not x.parent)


t = Tree()

为idCode,部分在product_dict.iteritems()中:
t.push(idCode,part.parent,part.name)
为t.roots中的节点:$ b​​ $ b节点。打印机()

考虑到我的产品是一架飞机的示例,现在的输出如下(实际订单不同):

 飞机
系统
子系统2
子系统1
子系统1.1
引擎
机身
第2节
第1节
第4节
第3节
pre>

但是,由于我在这个阶段对Python的理解有限,我正在努力为此添加字母排序(基于part.name字符串)。我明白树是如何建立的,但是我不能掌握打印程序,因此无法判断在哪里添加字母排序例程。



例如,我想要的输出应该是:

 飞机
机身
第1节
第2节
第3节
第4节
引擎
系统
子系统1
子系统1.1
子系统2

非常感谢任何帮助。我不坚持上面给出的分层排序方法,所以我开放的方法完全不一样。

解决方案

只有你需要做的事情是按照名字排序孩子,即打印时,即

 为排序的孩子(self.children, key = lambda x:x.name):
child.printer(level + 1)


I am using a Python dictionary (product_dict) to represent a hierarchy of a product and all its subparts. The dict's keys are unique IDs (UUID), and the values are Class objects containing all information about those parts, including:

part.name        # A string, containing the actual name of a component
part.idCode      # UUID of component
part.parent      # UUID of parent component
part.children    # List of UUIDs of child components
part.tier        # An integer that specifies its tier/level within the hierarchy

Now for the purpose of outputting the data in an orderly fashion, I wish to sort the parts both hierarchically and alphabetically. For hierarchical sorting using a tree structure, I have found the answer to this question to work great for printing: Sorting data hierarchically. For this example to work with my data structure, I have made some slight modifications:

class Node:
    def __init__(self, article):
        self.article = article
        self.children = []
        self.parent = None
        self.name = None 

    def printer(self, level=0):
        print ('{}{}'.format('\t' * level, self.name))
        for child in self.children:
            child.printer(level + 1)


class Tree:
    def __init__(self):
        self.nodes = {}

    def push(self, article, parent, name):                          
        if parent not in self.nodes:
            self.nodes[parent] = Node(parent)
        if article not in self.nodes:                              
            self.nodes[article] = Node(article)
        if parent == article:
            return
        self.nodes[article].name = name
        self.nodes[article].parent = self.nodes[parent]             
        self.nodes[parent].children.append(self.nodes[article])    

    @property
    def roots(self):
        return (x for x in self.nodes.values() if not x.parent)


t = Tree()

for idCode, part in product_dict.iteritems(): 
    t.push(idCode, part.parent, part.name)
for node in t.roots:
    node.printer()

Considering an example of my product being an aircraft, the output now looks as follows (the actual order varies):

Aircraft
    Systems
        Subsystem 2
        Subsystem 1
            Subsubsystem 1.1
    Engines
    Airframe
        Section 2
        Section 1
        Section 4
        Section 3

However, due to my limited understanding of Python at this stage, I am struggling to add alphabetical sorting to this routine (based on the part.name strings). I understand how the tree is built up, but I don't grasp the printing routine, and therefore fail to judge where to add a alphabetic sorting routine.

With the given example, my desired output should be:

Aircraft
    Airframe
        Section 1
        Section 2
        Section 3
        Section 4
    Engines     
    Systems
        Subsystem 1
            Subsubsystem 1.1
        Subsystem 2

Any help is greatly appreciated. I do not adhere to the hierarchical sorting method given above, so I am open to entirely different approaches.

解决方案

It seems like the only thing you need to do is sort the children by name, when printing, i.e.

 for child in sorted(self.children, key = lambda x: x.name):
        child.printer(level + 1)

这篇关于按字母顺序排列字典(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆