e1v1s
e1v1s

Reputation: 385

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?

Upvotes: 0

Views: 88

Answers (2)

QuantumEnergy
QuantumEnergy

Reputation: 406

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')}

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71461

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

Upvotes: 1

Related Questions