在Python中搜索和排序字典 [英] Search and sort through dictionary in Python
问题描述
我需要对字典进行排序和搜索.我知道字典无法排序.但是我需要做的就是以一种排序的格式搜索它.字典本身不需要排序.
I need to sort and search through a dictionary. I know that dictionary cannot be sorted. But all I need to do search through it in a sorted format. The dictionary itself is not needed to be sorted.
有2个值.作为键并与该键关联的字符串是整数值.我需要获取基于整数的排序表示形式.我可以通过OrderedDict获得它.
There are 2 values. A string, which is a key and associated with the key is an integer value. I need to get a sorted representation based on the integer. I can get that with OrderedDict.
但是我不需要打印整个字典,而只打印前50个值.我需要使用RegEx提取一些键.说出所有以"a"开头且长度为5的键.
But instead of the whole dictionary I need to print just the top 50 values. And I need to extract some of the keys using RegEx. Say all the keys starting with 'a' and of 5 length.
在旁注中,有人可以告诉我如何在python中以良好格式打印吗?像:
On a side note can someone tell me how to print in a good format in python? Like:
{'secondly': 2,
'pardon': 6,
'saves': 1,
'knelt': 1}
实际上是一行.谢谢您的时间.
insdead of a single line. Thank you for your time.
推荐答案
如果要基于整数值对字典进行排序,则可以执行以下操作.
If you want to sort the dictionary based on the integer value you can do the following.
d = {'secondly': 2, 'pardon': 6, 'saves': 1, 'knelt': 1}
a = sorted(d.iteritems(), key=lambda x:x[1], reverse=True)
a
将包含一个元组列表:
The a
will contain a list of tuples:
[('pardon', 6), ('secondly', 2), ('saves', 1), ('knelt', 1)]
您可以使用a[:50]
将其限制在前50位,然后使用您的搜索模式在各个键中进行搜索.
Which you can limit to a top 50 by using a[:50]
and then search through the keys, with youre search pattern.
这篇关于在Python中搜索和排序字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!