【问题标题】:Complex dictionary sorting复杂的字典排序
【发布时间】:2012-03-31 07:17:35
【问题描述】:

我有一个字典,键是单词,每个单词都有一个数字值。我想输出前 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}

【问题讨论】:

  • 排序是指按字母顺序排序!
  • 你能发布你目前所拥有的吗?
  • 请给出一个小示例字典和所需的输出。
  • 所以你只想要前 10 个值(可能有超过 10 个键),或者最多 10 个键值?如果是后者,如果最高值有 11 个键怎么办?并且您希望按键按字母顺序显示?
  • 请编辑您的问题以包含更新的信息以及您目前拥有的代码、说明为什么它不适合您以及您正在使用的数据。

标签: python sorting dictionary


【解决方案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]

【讨论】:

  • 不是值,而是键! :) 但是具有相同值的键是按字母顺序排列的!!
  • 这些是键...如何按字母顺序排列键,在您的情况下它们不是数字吗?
  • 键是单词,键的值是数字(int)。
【解决方案2】:

我不确定我是否完全理解,但您可以尝试以下方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 2013-09-14
    相关资源
    最近更新 更多