fheck
fheck

Reputation: 280

How to get first item of each tuple in a list / python

I've initialized a dict in python 3.3.3 like this one:

# dict with dates and name
my_dict = {'keyone': '2013-04-22', 'keytwo': '2013-04-25'}

I've sorted this dict reverse by values with the following snippet:

# sort reverse by value
my_list = sorted(my_dict.items(), key=lambda x:x[1], reverse=True)

# will output a list of tuples
[('keytwo', '2013-04-25'), ('keyone', '2013-04-22')]

Now I'm trying to get a list of the keys (first item of each tuple) in the same order:

# what I need
my_new_list = ['keytwo', 'keyone']

Hope someone can help me. It's very depressing and frustrative!

Lots of greetings,

felix

Upvotes: 2

Views: 2142

Answers (4)

Rusty Rob
Rusty Rob

Reputation: 17173

>>> d = {'keyone': '2013-04-22', 'keytwo': '2013-04-25'}
>>> sorted(d, key=d.get, reverse=True)
['keytwo', 'keyone']

Upvotes: 0

user2555451
user2555451

Reputation:

You can use a list comprehension:

>>> my_dict = {'keyone': '2013-04-22', 'keytwo': '2013-04-25'}
>>> my_list = sorted(my_dict.items(), key=lambda x:x[1], reverse=True)
>>> my_new_list = [x[0] for x in my_list]
>>> my_new_list
['keytwo', 'keyone']
>>>

Upvotes: 0

user2357112
user2357112

Reputation: 280564

List comprehension:

my_new_list = [key for key, value in my_list]

Or just produce a list of keys in the first place:

my_new_list = sorted(index_dict, key=index_dict.get, reverse=True)

Upvotes: 2

Joran Beasley
Joran Beasley

Reputation: 113978

new_list = map(operator.itemgetter(0),my_list)

Upvotes: 2

Related Questions