Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从groupby返回类似dict的结构_Python_Python 2.7 - Fatal编程技术网

Python 从groupby返回类似dict的结构

Python 从groupby返回类似dict的结构,python,python-2.7,Python,Python 2.7,以下是基本代码: from my_parser import data from itertools import groupby from collections import Counter def grades(date=datetime.now().strftime('%Y%m')): this_month = self.data.key_by('GRADE').pop(date) # this gives a list of this month monthly = dict

以下是基本代码:

from my_parser import data
from itertools import groupby
from collections import Counter

def grades(date=datetime.now().strftime('%Y%m')):
  this_month = self.data.key_by('GRADE').pop(date) # this gives a list of this month
  monthly = dict(groupby(this_month, lambda k: make_letter(k.GRADE))) # group it by letter grade
  c = [{
    'month': k,
    'total': len(x)
  } for k,x in monthly.iteritems()]
但是,字典返回的结果如下:

A : <itertools._grouper object at 0x1033f0c90>
C : <itertools._grouper object at 0x1033f0c50>
而不是

monthly = dict(groupby(this_month, lambda k: make_letter(k.GRADE))) # group it by letter grade
试一试


编辑:您可能需要在本月对等级进行预排序,以使等级按升序排列(或至少使与给定字母对应的所有等级显示在一起)。

通常,
\u grouper
对象是一个生成器,您可以通过执行
列表(x)
将其转换为列表(或元组,如果您愿意的话)……唉,唯一的问题是,它不喜欢在我正在使用的列表生成器中变成列表。每次我将它用作列表中的变量时,是否必须将其强制转换为列表?
monthly = dict(groupby(this_month, lambda k: make_letter(k.GRADE))) # group it by letter grade
monthly = {
    val:list(items)
    for val,items in
    groupby(this_month, lambda k: make_letter(k.GRADE))
}