从字典创建“顶级列表”

2024-06-16 10:18:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有字典,比如:

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

我需要创造这样的东西:

  1. Emily - 50
  2. John - 15
  3. Joey - 12
  4. Josh - 2

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


Tags: namenumber字典排序johnlistjosh办法
3条回答

简单的方法:

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

在这里看到答案:How do I sort a dictionary by value?

在您的情况下,您需要反转排序的\u x,因为您首先需要更高的值,因此:

import operator


x = {"John":15,"Josh":2,"Emily":50,"Joey":12}
sorted_x = sorted(x.items(), key=operator.itemgetter(1), reverse=True)

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

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

相关问题 更多 >