Sorting python dictionary by the keys
>>> the_values = [u'abc', u'kfc', u'listproperty', u'models', 开发者_StackOverflowu'new', u'newer', u'note', u'order', u'tag', u'test', u'type']
>>> the_keys = [1, 2, 1, 2, 1, 1, 1, 1, 2, 1, 1]
d2 = dict(zip(the_keys, the_values))
>>> d2
{1: u'type', 2: u'tag'}
Can you give me a clue why only "type" and "tag" are taken?
I am trying to sort the_values
by the_keys
.
I noticed that switching the order of the_values
and the_keys
works:
>>> d2 = dict(zip(the_values, the_keys))
>>> d2
{u'abc': 1, u'models': 2, u'note': 1, u'tag': 2, u'kfc': 2, u'newer': 1, u'listproperty': 1, u'test': 1, u'new': 1, u'type': 1, u'order': 1}
Thanks.
Keys must be unique, so using 1 and 2 as the only keys means you can only have two values associated with them.
When you're creating the dictionary, you're setting the key to correspond to a value. So first, 1 -> abc, 2 -> kfc. But then you're continually overriding the keys to give them different values. In the end, only the latest values for the keys are kept (1 -> type, 2-> tag).
As others have said, keys must be unique. In order to get around that, you must not use a dictionary.
>>> [x[1] for x in sorted(zip(the_keys, the_values), key=operator.itemgetter(0))]
[u'abc', u'listproperty', u'new', u'newer', u'note', u'order', u'test', u'type', u'kfc', u'models', u'tag']
Because a dictionary, by definition, has unique keys. (Otherwise, how would it know which value to return when you look up the key?) The dict
constructor iterates through the key-value pairs and assigns the value to the corresponding key in the dictionary, overwriting the previous value for keys that are already present.
精彩评论