代码之家  ›  专栏  ›  技术社区  ›  Arbys

从字典[副本]创建“顶级列表”

  •  -1
  • Arbys  · 技术社区  · 7 年前

    我有字典,比如:

    x = {"John":15,"Josh":2,"Emily":50,"Joey":12}
    

    我需要创建如下内容:

    1. 艾米丽-50
    2. 约翰-15
    3. 乔伊-12
    4. Josh-2

    最好的方法是什么?我已经尝试过以某种方式对字典进行排序,但后来它转换为list,我无法同时获得两个值(name和number)。

    3 回复  |  直到 7 年前
        1
  •  0
  •   RomanPerekhrest    7 年前

    通过字典值进行简单排序:

    x = {"John":15, "Josh":2, "Emily":50, "Joey":12}
    
    for i, t in enumerate(sorted(x.items(), key=lambda x: x[1], reverse=True), 1):
        print('{}. {} - {}'.format(i, t[0], t[1]))
    

    输出:

    1. Emily - 50
    2. John - 15
    3. Joey - 12
    4. Josh - 2
    
        2
  •  0
  •   Felix M    7 年前

    在此处查看答案: How do I sort a dictionary by value?

    在您的情况下,您需要先反转sorted\u x,因为您需要更高的值,所以:

    import operator
    
    
    x = {"John":15,"Josh":2,"Emily":50,"Joey":12}
    sorted_x = sorted(x.items(), key=operator.itemgetter(1), reverse=True)
    
        3
  •  0
  •   Mathieu    7 年前

    简单的方法:

    x = {"John":15,"Josh":2,"Emily":50,"Joey":12}
    
    val = sorted([y for y in x.values()])
    name = val[:]
    for key in x.keys():
        id = val.index(x[key])
        name[id] = key