【发布时间】:2012-11-21 15:30:58
【问题描述】:
现在我知道如何通过文件 txt 实现字典。 所以我创建了 example.txt(通用文件):
aaa.12
bbb.14
ccc.10
并制作字典:
with open('example.text') as f:
hash = {}
for line in f:
key, value = line.strip().split('.', 1)
hash[key] = int(value)
所以现在我想按价值订购我的元素:所以我尝试
with open('example.txt') as f:
hash = {}
for line in f:
key, value = line.strip().split('.', 1)
hash[key] = int(value)
print hash #this print my dict
value_sort=sorted(hash.values())
print value:sort #to check the what return and gave me in this case value_sort=[10, 12, 14]
完美,所以现在我如何在 example.txt 上写我的项目按价值排序:
ccc.10
aaa.12
bbb.14
【问题讨论】:
-
只是好奇,为什么对这个问题投反对票?
-
也许反对者认为您应该使用适当的序列化程序而不是自己发明。你可以使用pickle或json。
-
也许 - 由于语法不佳 - 投票者无法理解所要求的内容。