因此,有两个任务要在字典上同时执行。
例如
my_dict = { 'abc': 10, 'def':20, 'ghi':100, 'jkl':30, 'mno':101}
所以,如果我想要前3而忽略值为100
且101
的键
result_top3 = [ ('jkl',30), ('def',20), ('abc',10)]
现在我正在使用以下内容:
my_result = dict(Counter(my_dict).most_common()[:3])
但它有两个问题:
我希望有一种方法可以一次性完成,或者采用更加Pythonic高效的方式,而不是分两步完成,比如删除我不想要的键然后排序。
编辑:没有必要对完整字典进行排序。我只需要提取前10个结果及其值。
答案 0 :(得分:3)
过滤数据
[items for items in my_dict.items() if items[1] < 100]
按键值排序dict
sorted(my_dict.items(), key=lambda x: -x[1])
并完整解决方案
sorted([items for items in my_dict.items() if items[1] < 100], key=lambda x: -x[1])[:3]
答案 1 :(得分:2)
与@ BearBrown的答案几乎相同。但是使用内置功能并将其分解,一步一步地进行:
Python 3.6.3 (v3.6.3:2c5fed86e0, Oct 3 2017, 00:32:08)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.0.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from collections import OrderedDict
In [2]: my_dict = { 'abc': 10, 'def':20, 'ghi':100, 'jkl':30, 'mno':101}
# filter values out, can be `if v >= 100`(this is depends on condition)
In [3]: filtered_values = ((k, v) for k, v in my_dict.items() if v not in [100, 101])
In [4]: filtered_values
Out[4]: <generator object <genexpr> at 0x1060a9ca8>
In [5]: import operator
# sort by values(second element of key-value tuple) in reverse order
In [6]: top_three = sorted(filtered_values, key=operator.itemgetter(1), reverse=True)[:3]
In [7]: top_three
Out[7]: [('jkl', 30), ('def', 20), ('abc', 10)]
In [8]: OrderedDict(top_three)
Out[8]: OrderedDict([('jkl', 30), ('def', 20), ('abc', 10)])
最后,您将获得所需的OrderedDict
(dict
订单)。
答案 2 :(得分:2)
这样做 -
>>> my_dict = { 'abc': 10, 'def':20, 'ghi':100, 'jkl':30, 'mno':101}
>>> dict_tuple = my_dict.items()
>>> print dict_tuple
[('jkl', 30), ('abc', 10), ('ghi', 100), ('def', 20), ('mno', 101)]
>>> dict_tuple.sort(key=lambda x: x[1])
>>> print dict_tuple
[('abc', 10), ('def', 20), ('jkl', 30), ('ghi', 100), ('mno', 101)]
>>> print dict(dict_tuple[:3])
{'jkl': 30, 'abc': 10, 'def': 20}
答案 3 :(得分:1)
你可以逐步完成:
my_dict = { 'abc': 10, 'def':20, 'ghi':100, 'jkl':30, 'mno':101}
filterIt = [(x[1],x[0]) for x in my_dict.items() if x[1] not in [101,100]]
sortOfSorted = sorted(filterIt, reverse = True)
print (my_dict)
print(filterIt)
print (sortOfSorted)
结果是[0]
上带有“值”的元组列表 - 由于元组首先按[0]
排序,然后[1]
Dictionarys like sets本质上是无序的。并且为了找到最大的项目,你需要对所有项目进行排序,以获得前10名。
<强>输出强>:
{'jkl': 30, 'abc': 10, 'ghi': 100, 'def': 20, 'mno': 101}
[(30, 'jkl'), (10, 'abc'), (20, 'def')]
[(30, 'jkl'), (20, 'def'), (10, 'abc')]
答案 4 :(得分:1)
operator.itemgetter(1)
将按value
排序dict;并operator.itemgetter(0)
将按key
对字典进行排序
>>> import operator
>>> my_dict = { 'abc': 10, 'def':20, 'ghi':100, 'jkl':30, 'mno':101}
>>> sorted_my_dict = sorted(my_dict.items(), key=operator.itemgetter(1))
>>> sorted_my_dict
[('abc', 10), ('def', 20), ('jkl', 30), ('ghi', 100), ('mno', 101)]
>>> sorted_my_dict[:3]
[('abc', 10), ('def', 20), ('jkl', 30)]