<p>不要使用dict。您的数据似乎有相应的<em>模型</em></p>
<p>相反,创建一个适当的<a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow noreferrer">Python class</a>,一个<code>Creature</code>:</p>
<pre class="lang-py prettyprint-override"><code>class Creature:
__init__(self, name, date, habitat):
self.name = name
self.date = date
self.habitat = habitat
# etc.
</code></pre>
<p>在读取输入文件时,为每个数据分组创建新的<code>Creature</code>实例。将每个<code>Creature</code>添加到某种集合中:</p>
<pre class="lang-py prettyprint-override"><code>creatures = list()
with open(FinalFilePath, "r") as textfile:
sections = textfile.read().split("\n\n")
for section in sections:
lines = section.split("\n")
creatures.append(Creature(lines[0], lines[1])) # add more params?
</code></pre>
<p>下一步,<a href="https://stackoverflow.com/a/5824757/695787">add some boiler-plate methods (^{<cd4>}, etc.)</a>到<code>Creature</code>类,这样它就可以排序了</p>
<p>最后,只需使用<code>sorted(creatures)</code>,然后您的生物集合将根据<code>__lt__</code>逻辑进行排序</p>
<p><code>__lt__</code>的实现如下所示:</p>
<pre class="lang-py prettyprint-override"><code>def __lt__(self, other):
if self.name < other.name:
return True
elif self.name > other.name:
return False
elif self.date < other.date:
return True
elif self.date > other.date:
return False
else
# What happens if name and date are the same?
</code></pre>
<p>**或者,您可以使用<code>creatures = SortedList()</code>,然后在调用<code>creates.add(Creature(...))</code>时将每个项插入到正确的位置。最后不需要<code>sorted(creatures)</code>调用</p>