-1

I have dictionary, something like:

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

And I need to create something like this:

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

What would be the best way to do this? I have already tried to sort the dictionary somehow, but then it converted to list and I wasn't able to get both values (name and number).

Aurora0001
  • 13,139
  • 5
  • 50
  • 53
Arbys
  • 35
  • 1
  • 6

3 Answers3

0

With simple sorting by dictionary values:

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

The output:

1. Emily - 50
2. John - 15
3. Joey - 12
4. Josh - 2
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

See the answer here: How do I sort a dictionary by value?

In your case, you'll want to reverse sorted_x as you want higher values first, so:

import operator


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

An easy way:

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
Mathieu
  • 5,410
  • 6
  • 28
  • 55