对字典键内的列表进行排序

时间:2014-11-27 13:12:03

标签: python dictionary

我有一个字典,其中包含学生姓名作为关键字,然后是一个包含存储在里面的测试中3个分数的列表。

我需要按字母顺序输出密钥,并将列表按从高到低的顺序排序。

任何帮助都会受到大力赞赏。

def task3():
    import pprint
    classList = {}
    classSearch = input("Which class would you like to interrogate? ")
    try:
        with open("answers " + classSearch + ".txt", 'rb') as handle:
            classList = pickle.loads(handle.read())
    except IOError as error:
        print ("Sorry, this file does not exist")

    sortOption = int(input("Would you like sort the students in alphabetical order? Enter 1"))
    if sortOption == 1:

        #how do I sort the list in order, I guess I have to for loop over the dictionary to then be able to access the keys
        pprint.pprint(classList)

3 个答案:

答案 0 :(得分:1)

我认为这是你想要实现的目标:

dictionary = {'Louis': [2, 10, 1],
               'John': [6, 1, 16]
               }
for name in sorted(dictionary.keys()):
    print name
    print sorted(dictionary[name], reverse=True)

输出:

John
[16, 6, 1]
Louis
[10, 2, 1]

答案 1 :(得分:0)

d = {'foo1':[1, 2, 4], 'foo': [100, 123, 321]}
x = sorted(d.items())
for key, value in x:
    value.sort()
    value.reverse()
print x

  >>> 
[('foo', [100, 123, 321]), ('vishnu', [1, 2, 4])]

答案 2 :(得分:0)

Python词典是未排序的数据结构。其中一个问题是:

for sorted_key in sorted(classList.keys()):
  print sorted_key, sorted(classList[sorted_key], reverse=True)

在这里,您可以从字典中提取密钥并对其进行排序。下一步是为给定密钥排序列表值。