按(特定)键打印字典

Print out dictionary by (specific) key

我是 python 的新手,我有好几本词典(都有几乎相同的键),我想在打印出来时先显示某个键。 我知道字典无法排序,这不是我想要做的,我只想根据特定的键顺序打印它们。

这是我目前拥有的:

class Employees:
    def __init__(self, name, job, pay, age=None):
        self.name = name
        self.job = job
        self.pay = pay
        self.age = age

    def gatherAttrs(self):
        attrs = []
        for key in self.__dict__:
            attrs.append('%s = %s' % (key, getattr(self,key)))
        return ', '.join(attrs)

    def __str__(self):
        return '%s: %s' % (self.__class__.__name__, self.gatherattrs())


sarah = Employees("Sarah Hopkins", "nurse", 60000, 30)
bob = Employees("Bob Smith", "doctor", 90000)

print sarah
print bob

output:
Employees: job = nurse, pay = 60000, age = 30, name = Sarah Hopkins
Employees: job = doctor, pay = 90000, age = None, name = Bob Smith

我想要的是这个:

Employees: name = Sarah Hopkins, job = nurse, pay = 60000, age = 30

我希望键 'name'(存在于所有已转换为列表的字典中)成为第一个出现的键值对。

我不知道为了实现这个我是否需要将字典转换为列表然后使用索引(尽管如果我添加新属性这可能会在以后产生问题),或者我是否应该保留它们作为命令并做其他事情。

您可以使用 collections.OrderedDict。它的行为与常规 dict 非常相似,但它会记住输入的订单项。

由于您 类 具有固定属性,最简单的解决方案是显式迭代:

class Employees:
  def gatherAttrs(self):
    attrs = []
    for key in ["name", "job", "pay", "age"]:
        attrs.append('%s = %s' % (key, getattr(self,key)))
    return ', '.join(attrs)

或者,您可以仅对 一些 属性进行显式迭代。

class Employees:
  _iter_attr__prio = ["name"]
  def gatherAttrs(self):
    attrs = []
    for key in self._iter_attr__prio + [key for key in self.__dict__ if key not in self._iter_attr__prio]:
        attrs.append('%s = %s' % (key, getattr(self,key)))
    return ', '.join(attrs)

最后可以试试排序:

class Employees:
  _iter_attr__prio = ["name"]
  def gatherAttrs(self):
    attrs = []
    for key in sorted(self.__dict__, key=lambda key: self. _iter_attr__prio.index(key) if key in self. _iter_attr__prio else 0, reverse=True):
        attrs.append('%s = %s' % (key, getattr(self,key)))
    return ', '.join(attrs)