Reputation: 1
Hi I have problem with my program, the value of groupby obj can not be get after casting to dict object.
from itertools import groupby
raw = [
{"name": "A", "age": 20},
{"name": "A", "age": 20},
{"name": "A", "age": 21},
{"name": "A", "age": 21},
]
grouped = dict(groupby(raw, key=lambda x: x["age"]))
# A
for v in grouped:
print(list(grouped[v]))
del grouped, v
# End A
# B
grouped = groupby(raw, key=lambda x: x["age"])
for key, v_gen in grouped:
print(list(v_gen))
# End B
output:
[]
[]
[{'name': 'A', 'age': 20}, {'name': 'A', 'age': 20}]
[{'name': 'A', 'age': 21}, {'name': 'A', 'age': 21}]
why the part of A got empty list?
expected output:
[{'name': 'A', 'age': 20}, {'name': 'A', 'age': 20}]
[{'name': 'A', 'age': 21}, {'name': 'A', 'age': 21}]
[{'name': 'A', 'age': 20}, {'name': 'A', 'age': 20}]
[{'name': 'A', 'age': 21}, {'name': 'A', 'age': 21}]
Upvotes: -1
Views: 16
Reputation: 1
I found the answer at https://docs.python.org/3/library/itertools.html#itertools.groupby
The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible.
Upvotes: 0