【问题标题】:Sort dictionary of tuples & take first entry python对元组字典进行排序并获取第一个条目 python
【发布时间】:2017-09-22 00:06:09
【问题描述】:

我有一本具有这种结构的长字典:

{'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

变成单线?

【问题讨论】:

  • 试试next(iter(sorted_by_integer.items()))。这个输出够吗?

标签: python dictionary tuples ordereddictionary


【解决方案1】:

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

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

【讨论】:

  • 当我尝试这个时,我只会在列表中找回钥匙。我错过了什么吗?
  • @e1v1s 是的,这只会给你排序的键。如果这不是您要查找的内容,请具体说明吗?
【解决方案2】:
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

输出:
{'key2': (2, 's2')}

【讨论】:

  • 这就是你想要的吗? @e1v1s
猜你喜欢
  • 1970-01-01
  • 2020-12-04
  • 2021-07-16
  • 2011-11-13
  • 1970-01-01
  • 2015-11-11
  • 2017-08-21
  • 1970-01-01
  • 2018-10-19
相关资源
最近更新 更多