Sort values and return list of keys from dict python [closed]?

Use sorted with the get method as a key (dictionary keys can be accessed by iterating): sorted(A, key=A. Get).

2 This is incorrect as it will only sort the keys, not sort the keys by their values. – David Wolever Sep 7 '11 at 20:20 1 but this, returns a list sorted by keys. I need a list of keys sorted by values.

:) – Alejandro Sep 7 '11 at 20:21 2 @David Wolever Oops, you're totally right. Fixed. – phihag Sep 7 '11 at 20:23.

Use sorted's key argument sorted(d, key=d. Get).

Sorted(a.keys(), key=a. Get) This sorts the keys, and for each key, uses a. Get to find the value to use as its sort value.

Note that it is unnecessary to use a. Keys, which makes a list of the keys. A (or a.iterkeys()) is already an iterable over the keys of the dict a.

– Mike Graham Sep 7 '11 at 20:26 1 Yeah, I know it's unnecessary, but I think it reads better. I think of dicts as containers of pairs, not containers of keys. – Ned Batchelder Sep 7 '11 at 22:20.

I'd use: items = dict.items() items. Sort(key=lambda item: (item1, item0)) sorted_keys = item0 for item in items The key argument to sort is a callable that returns the sort key to use. In this case, I'm returning a tuple of (value, key), but you could just return the value (ie, key=lambda item: item1) if you'd like.

The other solution is simpler and easier to read for me. – Mike Graham Sep 7 '11 at 20:28 thans @David but doing this, I only got the first key correct. :( – Alejandro Sep 7 '11 at 20:29 It sounds like your data are funky then… Are they exactly like the ones you posted above?

– David Wolever Sep 7 '11 at 20:38 not exactly, my dict is like {'name1':34, 'name2': 89, 'name3': 25,'name4': 45, 'name5':890,...} and after did what you said, I got something like this: names5, name1, name2, name4, name3,... – Alejandro Sep 7 '11 at 20:44 sorry sorry, I was doing some stupid thing... you was right! :) – Alejandro Sep 7 '11 at 20:52.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions