Recently, I encountered a requirement to group a nested dictionary in a list according to a value of the dictionary

The following

a = [{"name": 'tom', "age": '18'}, {"name": "jack", "age": "42"}, {"key": "lily", "age": "18"}]
Copy the code

We need to group dictionaries with the same age

The solution

from itertools import groupby
from operator import itemgetter

rows = [{"name": 'tom', "age": 1}, {"name": "jack", "age": 12}, {"name": "lily", "age": 12}]

for date, items in groupby(sorted(rows, key=itemgetter('age')), key=itemgetter('age')):
    print(date,list(items))
Copy the code

cookies

At the end of this step, I found that when the value of item was fetched in the last for loop, the fetched content was empty. I thought that there was an operation on items during the implementation of the built-in module, so I made a deep copy to solve the problem

from itertools import groupby
from operator import itemgetter
import copy

rows = [{"name": 'tom', "age": 1}, {"name": "jack", "age": 12}, {"name": "lily", "age": 12}]

for date, items in groupby(sorted(rows, key=itemgetter('age')), key=itemgetter('age')):
    items = copy.deepcopy(items)
    print(date,list(items))
Copy the code

Thanks to the comment section, the error has been corrected!