我有一个python词典列表。现在,我如何将这些字典合并到python中的单个实体中。字典示例是
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"]}]
输出应为:
[{"name":"kishore", "playing":["cricket","basket ball","volley ball","hockey"]},{"name":"xyz","playing":["cricket"]}]
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 itertools
import operator
by_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'}]
产品:
toutput = {}
for entry in input_dictionary:
if entry['name'] not in toutput: toutput[entry['name']] = []
for p in entry['playing']:
if p not in toutput[entry['name']]:
toutput[entry['name']].append(p)
output = list({'name':n, 'playing':l} for n,l in toutput.items())
或使用集合:
[{'name': 'kishore', 'playing': ['cricket', 'basket ball', 'volley ball', 'hockey']}, {'name': 'xyz', 'playing': ['cricket']}]
这基本上是@perreal答案的细微变化(我是说,是在from collections import defaultdict
toutput = defaultdict(set)
for entry in input_dictionary:
toutput[entry['name']].update(entry['playing'])
output = list({'name':n, 'playing':list(l)} for n,l in toutput.items())
版本添加之前的答案!)
defaultdict
merged = {}
for d in input_dictionary:
merged.setdefault(d["name"], set()).update(d["playing"])
output = [{"name": k, "playing": list(v)} for k,v in merged.items()]