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.