我如何对字典元素进行排序:
with open('directory file txt','r') as f:
for line in f:
keys = line.strip().split('.')
value = keys[-1]
for key in reversed(keys[1:-1]):
value = {key: value}
result[keys[0]]=value
现在,如果打印键我有:
['a','b','c','d','1']
['a','f','e','d','3']
['f','b','c','d','2']
['a','b','c','d','0']
我可以通过最后一个元素订购每个元素并将其保存到文件中吗? 所以我的输出将是:
a.b.c.d.0
a.b.c.d.1
f.b.c.d.2
a.f.e.d.3
答案 0 :(得分:1)
您不需要字典。您可以按列表阅读这些行:
with open('directory file txt','r') as f:
lines = f.readlines()
然后通过指定排序键直接对列表进行排序:
lines.sort(key = lambda s: int(s.rsplit('.', 1)[1]))