2012-03-31 108 views
-2

我有一個字典,其中的鍵是單詞,每個單詞的值都是一個數字。我想輸出鍵的前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

並通過區分我的意思是按照字母順序排列! – 2012-03-31 07:17:58

+2

你可以發佈你迄今爲止的? – jgritty 2012-03-31 07:18:58

+0

請給出一個小例子字典和所需的輸出。 – 2012-03-31 07:19:47

回答

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] 
+0

不是值,鑰匙! :)但具有相同值的鍵是按字母順序排列的! – 2012-03-31 11:55:41

+0

這些是鑰匙...鑰匙按字母順序排列的不是他們的數字在你的情況? – jamylak 2012-03-31 12:01:32

+0

鍵是單詞,鍵的值是數字(int)。 – 2012-03-31 15:48:01

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