我是python的新手,我有几个词典(所有词都有相同的键),我想在打印出来时首先显示某个键。 我知道dicts无法排序,这不是我想做的事情,我只是想根据特定的按键顺序打印它们。
这是我到目前为止所做的:
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'(存在于所有dicts中 - 已转换为list-)成为第一个出现的键值对。
我不知道为了实现这一点,我需要将dicts转换为列表,然后使用索引(即使这可能会在以后添加新属性时产生问题),或者我应该将它们保留为dicts并做点别的事。
答案 0 :(得分:0)
您可以使用collections.OrderedDict
。它几乎就像常规的dict
,但它会记住输入的订单项。
答案 1 :(得分:0)
由于您拥有具有固定属性的类,因此最简单的解决方案是显式迭代:
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)