python列表字典嵌套时,如何对字典value值相同的进行分组?
python">a = [{"name": 'tom', "age": '18'}, {"name": "jack", "age": "42"}, {"key": "lily", "age": "18"}]
如何把age相同的字典分组取出来呢??
回答:
from itertools import groupbyfrom operator import itemgetter
rows = [{"name": 'tom', "age": 1}, {"name": "jack", "age": 12}, {"name": "lily", "age": 12}]
for date, items in groupby(rows, key=itemgetter('')):
print (date,list(items))
回答:
import pandas as pda = [
{"name": 'tom', "age": '18'},
{"name": "jack", "age": "42"},
{"name": "lily", "age": "18"}]
df = pd.DataFrame(a)
res = [{"age":k, "name":g["name"].tolist()} for k, g in df.groupby("age")]
print(res)
[{'age': '18', 'name': ['tom', 'lily']}, {'age': '42', 'name': ['jack']}]
以上是 python列表字典嵌套时,如何对字典value值相同的进行分组? 的全部内容, 来源链接: utcz.com/a/160574.html