0

现在我知道如何通过文件 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
4

1 回答 1

0

You'll need to loop through the hash dict separately, where you ask it to be sorted on value:

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)

The sorted() call is given a key to sort by, namely the second element of each .items() tuple (a key and value pair).

If you wanted to write the sorted items to a file, you'd need to open that file in writing mode:

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))

Note that we write newlines (\n) after every entry; print includes a newline for us but when writing to a file you need to include it manually.

于 2012-11-21T15:43:10.787 回答