如何在列表/ python中获取每个元组的第一项

时间:2014-01-09 23:59:15

标签: python list key

我在python 3.3.3中初始化了一个像这样的dict:

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

我已使用以下代码段将此dict反向排序:

# 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')]

现在我想以相同的顺序获取密钥列表(每个元组的第一项):

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

希望有人可以帮助我。这非常令人沮丧和令人沮丧!

很多问候,

费利克斯

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

列表理解:

my_new_list = [key for key, value in my_list]

或者只是首先生成一个键列表:

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

答案 2 :(得分:0)

您可以使用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']
>>>

答案 3 :(得分:0)

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