Using a dictionary, how do I keep Values and Keys together after sorting the keys?

时间:2017-04-24 17:28:09

标签: python dictionary

I have a dictionary, with a name (key) and a score (value) where I remove all of the values, and then sort them using a merge sort. But how do I then make a new dictionary with the new sorted list of values but with their original key if that makes sense?

I have searched around before asking, and only really found ways to sort a dictionary as a whole, but I want to use a merge sort I have made, which I do not think is possible with a dictionary. Any help is appreciated, thanks.

1 个答案:

答案 0 :(得分:0)

You can search back the keys, one by one, with a dictionary comprehension like {k: a[k] for k in sorted(a)}. Alternatively, you can sort a.items() which would keep the key-value pairs in the format of tuples:

>>> a = {'a': 1, 'b': 2, 'c': 3}

# using sorted(a.items()) (keys and values reserved)

>>> sorted(a.items())
[('a', 1), ('b', 2), ('c', 3)]

>>> {k: v for k, v in sorted(a.items())}
{'a': 1, 'b': 2, 'c': 3}

# using sorted(a) (only keys reserved)

>>> [(k, a[k]) for k in sorted(a)]
[('a', 1), ('b', 2), ('c', 3)]

>>> {k: a[k] for k in sorted(a)}
{'a': 1, 'b': 2, 'c': 3}