现在我知道如何通过文件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
答案 0 :(得分:0)
你需要单独遍历hash
dict,在那里你要求它按值排序:
from operator import itemgetter
hash = {}
with open('example.text') as f:
for line in f:
key, value = line.strip().split('.', 1)
hash[key] = int(value)
for key, value in sorted(hash.items(), key=itemgetter(1)):
print '{0}.{1}'.format(key, value)
sorted()
调用被赋予一个排序依据,即每个.items()
元组的第二个元素(一个键和值对)。
如果您想将已排序的项目写入文件,则需要以书面模式打开该文件:
with open('example.txt', 'w') as f:
for key, value in sorted(hash.items(), key=itemgetter(1)):
f.write('{0}.{1}\n'.format(key, value))
请注意,我们会在每个条目后写下换行符(\n
); print
包含换行符,但在写入文件时,您需要手动添加。