对元组字典进行排序&先进入python

时间:2017-09-22 00:06:09

标签: python dictionary tuples ordereddictionary

我有一个有这种结构的长词典:

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

我希望按integer1&排序字典。拿第一个条目。

这是我到目前为止所拥有的:

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

我的问题是我可以凝聚......

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

进入单线?

2 个答案:

答案 0 :(得分:1)

使用单行表达式,您可以使用值中的整数作为排序键,按排序顺序检索字典的键:

s = {'key': (integer1, 'string1')} 
new_data = [a for (a, (b, c)) in sorted(s.items(), key=lambda x: x[-1][0])]

答案 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

<强>输出:
{&#39; key2&#39;:(2,&#39; s2&#39;)}