python 字典键 列表
The itertools function in Python provides an efficient way for looping lists, tuples and dictionaries. The itertools.groupby function in itertools will be applied in this tutorial to group a list of dictionaries by a particular key.
Python中的itertools函数提供了一种有效的循环列表,元组和字典的方法。 itertools中的itertools.groupby函数将在本教程中应用,以按特定键对字典列表进行分组。
To illustrate how this works, we will look at a list of students info (in dictionaries) and try to group these by “class” key such that at the end we will have a list of lists with the inner list being students in the same class.
为了说明这是如何工作的,我们将查看一个学生信息列表(在词典中),并尝试按“班级”键对这些信息进行分组,以便最后我们将获得一个列表列表,而内部列表属于同一学生类。
Please note that the sorted function must be called before the groupby.
请注意,必须在groupby之前调用已排序的函数。
import operatorimport itertoolsd = [{"name":"tobi","class":"1","age":"14", "gender":"m"},{"name":"joke","class":"1","age":"18", "gender":"f"}, {"name":"mary","class":"2","age":"14", "gender":"f"},{"name":"kano","class":"2","age":"15", "gender":"m"},{"name":"ada","class":"1","age":"15", "gender":"f"},{"name":"bola","class":"2","age":"10", "gender":"f"},{"name":"nnamdi","class":"1","age":"15", "gender":"m"}]d = sorted(d, key=operator.itemgetter("class"))outputList=[]for i,g in itertools.groupby(d, key=operator.itemgetter("class")): outputList.append(list(g))This same result can be achieved by executing nested looping in some ways, however, “itertools.groupby” function is faster and more efficient — and if I could add, neater.
通过以某种方式执行嵌套循环也可以达到相同的结果,但是,“ itertools.groupby”功能更快,更高效-如果可以的话,可以更整洁。
In the case when two or more python dictionaries are to be considered for the grouping, simply add the remaining keys in the “itemgetter” functions. The following code block shows the case when the students are expected to be grouped by class and gender.
如果要考虑两个或多个python字典进行分组,只需在“ itemgetter”函数中添加其余键即可。 以下代码块显示了按班级和性别对学生进行分组的情况。
import operatorimport itertoolsd = [{"name":"tobi","class":"1","age":"14", "gender":"m"},{"name":"joke","class":"1","age":"18", "gender":"f"}, {"name":"mary","class":"2","age":"14", "gender":"f"},{"name":"kano","class":"2","age":"15", "gender":"m"},{"name":"ada","class":"1","age":"15", "gender":"f"},{"name":"bola","class":"2","age":"10", "gender":"f"},{"name":"nnamdi","class":"1","age":"15", "gender":"m"}]d = sorted(d, key=operator.itemgetter("class","gender"))outputList=[]for i,g in itertools.groupby(d,key= operator.itemgetter("class","gender")): outputList.append(list(g))That’s it!
而已!
翻译自: https://medium.com/@hifywork/grouping-list-of-dictionaries-by-specific-key-s-in-python-61edafbbc0ed
python 字典键 列表
相关资源:微信小程序源码-合集6.rar