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
new_list = map(operator.itemgetter(0),my_list)
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)
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']
>>>
>>> d = {'keyone': '2013-04-22', 'keytwo': '2013-04-25'}
>>> sorted(d, key=d.get, reverse=True)
['keytwo', 'keyone']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.