如何存储itertools查询的输出

时间:2017-10-04 13:28:51

标签: python

我有以下查询

for key, group in itertools.groupby(r, lambda item: item['b_id']):
        print {key: [x['a_id'] for x in group]}

给出输出

{'0d687c94c5f4': ['12345', '67890']}
{'9ec34be3d535': ['23857', '84596']}
{None: ['d82ebe9815cc']}

如何将其存储到变量以访问其内容

尝试了data = {key:[x [' a_id'] for x in group]}但是只给出了循环中的最后一个值{None:[' d82ebe9815cc']}

>>data 
>>{None: ['d82ebe9815cc']}

1 个答案:

答案 0 :(得分:0)

您正在每次迭代时使用单个键创建一个新字典。相反,首先定义一个字典,然后在循环中添加键:

data = {key: [x['a_id'] for x in group] for key, group in
        itertools.groupby(r, lambda item: item['b_id'])}

或者,您可以使用字典理解(Python 2.7 +):

https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/spreadsheets