我有一个字典,其中的键是单词,每个单词的值都是数字。我想输出前10个最大的键值,但我有多个具有相同值的键。如何显示按字母顺序排序的键以及其他键(独特值)或排序(与其他键共享相同值)?
这是我的字典!
{'callooh': 1, 'all': 2, 'beware': 1, 'through': 3, 'eyes': 1, 'its': 1, 'callay': 1,
'jubjub': 1, 'to': 1, 'frumious': 1, 'wood': 1, 'tulgey': 1, 'has': 1, 'his': 2,
'"beware': 1, 'one': 2, 'day': 1, 'mome': 2, 'uffish': 1, 'manxome': 1, 'did': 2,
'galumphing': 1, 'whiffling': 1, '`twas': 1, 'went': 2, 'outgrabe': 2, 'slithy': 2,
'blade': 1, 'bandersnatch!"': 1, 'jaws': 1, 'snicker-snack': 1, 'back': 1, 'dead': 1,
'stood': 2, 'foe': 1, 'bird': 1, 'claws': 1, 'joy': 1, 'shun': 1, 'come': 1, 'by': 1,
'boy': 1, 'raths': 2, 'thou': 1, 'of': 1, 'o': 1, 'toves': 2, 'son': 1, '"and': 1,
'slain': 1, 'twas': 1, 'brillig': 2, 'bite': 1, 'two': 2, 'long': 1, 'head': 1, 'that': 2,
'took': 1, 'vorpal': 2, 'arms': 1, 'catch': 1, 'with': 2, 'he': 7, 'wabe': 2,
'tree': 1, 'flame': 1, 'were': 2, 'chortled': 1, 'beamish': 1, **'and': 13**,
'gimble': 2, 'it': 2, 'as': 2, 'in': 6, 'sought': 1, 'my': 3, 'awhile': 1, 'mimsy': 2,
'sword': 1, 'borogoves': 2, 'hand': 1, 'rested': 1, 'frabjous': 1, 'gyre': 2,
'tumtum': 1, 'thought': 2, 'so': 1, 'time': 1, 'jabberwock': 3, **'the': 19**,
'burbled': 1, 'came': 2, 'left': 1}
答案 0 :(得分:1)
我不确定我完全理解,但你可以尝试类似的东西:
# Assuming the data you're working with is something like:
>>> d = {'apple': 10, 'banana': 10, 'pear': 5, 'peach': 35, 'plum': 17, 'tomato': 17}
# Use - to order by values descending, key ordering will still be ascending.
>>> sorted(d.items(), key = lambda kv: (-kv[1], kv[0]))
[('peach', 35),
('plum', 17),
('tomato', 17),
('apple', 10),
('banana', 10),
('pear', 5)]
答案 1 :(得分:1)
>>> from itertools import islice, chain, repeat
>>> food = {1: ['apple', 'chai', 'coffe', 'dom banana'], 2: ['pie', 'tea'], 3: ['bacon', 'pepsi'], 4: ['strawberry'], 5: ['egg'], 7: ['cake', 'ham'], 9: ['milk', 'mocha'], 10: ['pear'], 11: ['chicken', 'latte'], 13: ['coke'], 20: ['chocolate']}
>>> list(islice(chain.from_iterable(repeat(k, len(v))
for k, v in
sorted(food.iteritems(), reverse=True)), 10))
[20, 13, 11, 11, 10, 9, 9, 7, 7, 5]