0

This question is a part of my current problem, so let's start with the big picture.

I am trying to sort a dictionary by the values in descending order. My dictionary is 1-to-1 corresponding, such as:

('ID1':value1, 'ID2':value2, ......)

I followed this thread and find my answer:

import operator
sorted_dict = sorted(original_dict.iteritems(), key = operator.itemgetter(1), reverse = True)

Then I tried to extract the keys in sorted_dict since I thought it is a dictionary. However, it turns out that sorted_dict is a list, thus has no keys() method.

In fact, the sorted_dict is organized as:

[('ID1', value1), ('ID2', value2), .....] # a list composed of tuples

But what I need is a list of ids such as:

['ID1', 'ID2', ......]

So now, the problem turns to How to extract variable in specific position for each of the tuples in a list?

Any suggestions? Thanks.

Community
  • 1
  • 1
ChangeMyName
  • 7,018
  • 14
  • 56
  • 93
  • Have a look at OrderedDict: http://docs.python.org/2/library/collections.html#collections.OrderedDict – Don Mar 27 '14 at 14:50

3 Answers3

3

You can do that using list comprehension as follows:

>>> ids = [element[0] for element in sorted_dict]
>>> print ids
['ID1', 'ID2', 'ID3', ...]

This gets the first element of each tuple in the sorted_dict list of tuples

sshashank124
  • 31,495
  • 9
  • 67
  • 76
1

Using list comprehension:

[i for (i,_) in sorted_dict]

should solve your problem

fredtantini
  • 15,966
  • 8
  • 49
  • 55
0

Use map plus itemgetter to process a list and get the first element

import operator
first_elements = map(operator.itemgetter(0), sorted_list)
Don
  • 16,928
  • 12
  • 63
  • 101