使用
itertools.groupby:
input_dictionary = [{"name":"kishore", "playing":["cricket","basket ball"]}, {"name":"kishore", "playing":["volley ball","cricket"]}, {"name":"kishore", "playing":["cricket","hockey"]}, {"name":"kishore", "playing":["volley ball"]}, {"name":"xyz","playing":["cricket"]}]import itertoolsimport operatorby_name = operator.itemgetter('name')result = []for name, grp in itertools.groupby(sorted(input_dictionary, key=by_name), key=by_name): playing = set(itertools.chain.from_iterable(x['playing'] for x in grp)) # If order of `playing` is important use `collections.OrderedDict` # playing = collections.OrderedDict.fromkeys(itertools.chain.from_iterable(x['playing'] for x in grp)) result.append({'name': name, 'playing': list(playing)})print(result)
输出:
[{'playing': ['volley ball', 'basket ball', 'hockey', 'cricket'], 'name': 'kishore'}, {'playing': ['cricket'], 'name': 'xyz'}]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)