简体   繁体   中英

Sort dictionary of tuples & take first entry python

I have a long dictionary with this structure:

{'key': (integer1, 'string1')}

and I want to sort the dictionary by integer1 & take the first entry.

Here's what I have so far:

sorted_by_integer = OrderedDict(sorted(tuple_dict.items(),key=lambda x:x[0], reverse=True))
keys = list(sorted_by_integer)
value = sorted_by_integer[keys[0]]
first_entry = {}
first_entry[keys[0]] = value

My question is can I condense...

first_entry = {}
first_entry[keys[0]] = value

into a one-liner?

Using a one line expression, you can retrieve the keys of the dictionary in sorted order using the integer in the value as the sort key:

s = {'key': (integer1, 'string1')} 
new_data = [a for (a, (b, c)) in sorted(s.items(), key=lambda x: x[-1][0])]
from collections import OrderedDict
s = {'key': (4, 'string1'), 'key2':(2, 's2'), 'key3':(3, 's3')}
s = dict(sorted(s.items(), key=lambda x: x[-1][0])[:1])
print s

output:
{'key2': (2, 's2')}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM