从字典列表到具有相同值的字典列表

时间:2019-08-16 12:40:08

标签: python

我有字典列表

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'}]

如何制作按键UserID分组的字典列表?

所以我想将具有键UserID的相同值的字典分组到列表中。

我希望这样:

[[{'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'}]]

3 个答案:

答案 0 :(得分:2)

首先根据import pandas as pd import operator import more_itertools as mit # Define starting DataFrame df = pd.DataFrame(data={'id': ['x', 'y', 'z'], 'foo_col': ['nothing', 'to', 'see'], 'A': [2, 0, 1], 'B': [0, 0, 3], 'C': [1, 3, 2], 'D': [1, 2, 2]}) print('Original DataFrame') print(df.to_string()) print() # Define 'source' and 'target' columns w_columns = ['A', 'B', 'C', 'D'] w_labels = ['W1', 'W2', 'W3'] # Define function to do this pivoting def pivot_w(row, columns=w_columns, labels=w_labels): # Convert relevant columns of DF to dictionary row_dict = row[columns].to_dict() # Convert dictionary to list of tuples row_tuples = [tuple(d) for d in row_dict.items()] # Sort list of tuples based on the second item (the value in the cell) row_tuples.sort(key=operator.itemgetter(1), reverse=True) # Get the sorted 'column' labels row_list = [x[0] for x in row_tuples if x[1] != 0] # Enforce rules 2 and 3 if len(row_list) < 3: row_list = list(mit.take(3, mit.padnone(row_list))) else: row_list = row_list[:3] # Create a dictionary using the W lables output = {i: j for i, j in zip(labels, row_list)} return output # Get DataFrame with W columns and index df_w = pd.DataFrame(list(df.apply(pivot_w, axis=1))) # Merge DataFrames on index df = df.merge(df_w, how='inner', left_index=True, right_index=True) # Drop A, B, C, D columns df.drop(columns=w_columns, inplace=True) print('Final DataFrame') print(df.to_string()) dict_list进行排序,然后使用UserID对基于itertools.groupby的结果进行分组

UserID

答案 1 :(得分:1)

也可以像这样使用列表理解:

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)

答案 2 :(得分:0)

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)