-4

I need to sort a dictionary containing a set of keys and values, the keys all differ as do the values and I need to sort the values though insertion sort before exporting to a file.

So far all I can find is people sorting either lists of multiple dictionaries where all the keys being sorted are the same.

my code is below:

playerName = ['a','b','c','d','e','f','g','h','i','j','k','l','m']
playerScore = [12,15,31,26,94,13,16,12,11,85,70,14,56]
player = dict(zip(playerName, playerScore))

print(player)

how do i now sort this?

Thanks

2 Answers2

1

Rather than using a dictionary, consider this:

playerName = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']
playerScore = [12, 15, 31, 26, 94, 13, 16, 12, 11, 85, 70, 14, 56] 

player = sorted(zip(playerName, playerScore), key=lambda x: x[0])

print(player)
[('a', 12),
 ('b', 15),
 ('c', 31),
 ('d', 26),
 ('e', 94),
 ('f', 13),
 ('g', 16),
 ('h', 12),
 ('i', 11),
 ('j', 85),
 ('k', 70),
 ('l', 14),
 ('m', 56)]

Just call python's inbuilt sorted function and pass a lambda function as a parameter so it knows what to sort on.


If you want to construct an ordered dictionary, you could use collections.OrderedDict (python < 3.6):

from collections import OrderedDict

player_dict = OrderedDict(sorted(zip(playerName, playerScore), key=lambda x: x[0]))
print(player_dict)
OrderedDict([('a', 12),
             ('b', 15),
             ('c', 31),
             ('d', 26),
             ('e', 94),
             ('f', 13),
             ('g', 16),
             ('h', 12),
             ('i', 11),
             ('j', 85),
             ('k', 70),
             ('l', 14),
             ('m', 56)])

It's still a dictionary, and supports all dict methods:

print(isinstance(player_dict, dict)
True

Note that dictionaries in python3.6+ are ordered by default, so just pass a list of tuples from sorted to dict and you'll get the same sorted result.

cs95
  • 379,657
  • 97
  • 704
  • 746
0

i think better to use playerscores as keys. if you use palyerscores as keys then you can get the keys and you can sort the keys. then you can find the best scorer and lowest scorer.

playerName = ['a','b','c','d','e','f','g','h','i','j','k','l','m']
playerScore = [12,15,31,26,94,13,16,12,11,85,70,14,56]
player = dict(zip(playerScore, playerName))
PList = []
for i in player.keys():
    PList.append(i)
PList.sort()
print(PList)
print(player)
chashikajw
  • 592
  • 5
  • 18