简体   繁体   中英

from list of dicts to list of lists of dicts with same values

I have list of dicts:

dict_list = [{'Id': 0, 'UserID': 1, 'Name': 'John'},
             {'Id': 1, 'UserID': 2, 'Name': 'Martin'},
             {'Id': 2, 'UserID': 1, 'Name': 'Rob'},
             {'Id': 3, 'UserID': 1, 'Name': 'Neil'},
             {'Id': 4, 'UserID': 2, 'Name': 'Bill'}]

How to make a list of lists of dicts that grouped by key UserID ?

So I want to group dicts with the same value of key UserID to lists.

I expect smth like that:

[[{'Id': 0,'UserID': 1, 'Name': 'John'},
  {'Id': 2,'UserID': 1, 'Name': 'Rob'},
  {'Id': 3,'UserID': 1, 'Name': 'Neil'}],
 [{'Id': 1,'UserID': 2, 'Name': 'Martin'}, 
  {'Id': 4,'UserID': 2, 'Name': 'Bill'}]]

First sort the dict_list based on UserID and then use itertools.groupby to group the results based on UserID

>>> from itertools import groupby
>>> key = lambda d: d['UserID']
>>> res = [list(grp) for _,grp in groupby(sorted(dict_list, key=key), key)]
>>> 
>>> pprint(res)
[[{'Id': 0, 'Name': 'John', 'UserID': 1},
  {'Id': 2, 'Name': 'Rob', 'UserID': 1},
  {'Id': 3, 'Name': 'Neil', 'UserID': 1}],
 [{'Id': 1, 'Name': 'Martin', 'UserID': 2},
  {'Id': 4, 'Name': 'Bill', 'UserID': 2}]]

It's also possible to use list comprehension like this:

dict_list = [{'Id': 0, 'UserID': 1, 'Name': 'John'},
         {'Id': 1, 'UserID': 2, 'Name': 'Martin'},
         {'Id': 2, 'UserID': 1, 'Name': 'Rob'},
         {'Id': 3, 'UserID': 1, 'Name': 'Neil'},
         {'Id': 4, 'UserID': 2, 'Name': 'Bill'}]

user_ids=set([x['UserID'] for x in dict_list])
result_list=[]
for user_id in user_ids:
    user_id_list = [x for x in dict_list if x['UserID']==user_id]
    result_list.append(user_id_list)

print(result_list)
from itertools import groupby
dict_list = [{'Id': 0, 'UserID': 1, 'Name': 'John'},
             {'Id': 1, 'UserID': 2, 'Name': 'Martin'},
             {'Id': 2, 'UserID': 1, 'Name': 'Rob'},
             {'Id': 3, 'UserID': 1, 'Name': 'Neil'},
             {'Id': 4, 'UserID': 2, 'Name': 'Bill'}]
res =[list(group) for _,group in groupby(sorted(dict_list, key=lambda f: f['UserID']), lambda f: f['UserID'])]
print(res)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM