在 Python 中,经常需要合并多个字典列表中的数据形成一个单一实体。例如,你可能有一个包含多个用户信息的字典列表,现在需要将这些字典合并成一个单一实体,以便于处理和分析数据。
2. 解决方案:
(1)使用 itertools.groupby:
import itertools
import operator
def merge_dicts(input_dictionary):
"""
Merge a list of dictionaries into a single entity.
Args:
input_dictionary (list): A list of dictionaries.
Returns:
list: A list of merged dictionaries.
"""
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))
result.append({'name': name, 'playing': list(playing)})
return result
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"]}
]
print(merge_dicts(input_dictionary))
输出:
[{'name': 'kishore', 'playing': ['volley ball', 'basket ball', 'hockey', 'cricket']}, {'name': 'xyz', 'playing': ['cricket']}]
(2)直接迭代和合并:
def merge_dicts(input_dictionary):
"""
Merge a list of dictionaries into a single entity.
Args:
input_dictionary (list): A list of dictionaries.
Returns:
list: A list of merged dictionaries.
"""
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())
return output
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"]}
]
print(merge_dicts(input_dictionary))
输出:
[{'name': 'kishore', 'playing': ['cricket', 'basket ball', 'volley ball', 'hockey']}, {'name': 'xyz', 'playing': ['cricket']}]
(3)使用默认字典:
from collections import defaultdict
def merge_dicts(input_dictionary):
"""
Merge a list of dictionaries into a single entity.
Args:
input_dictionary (list): A list of dictionaries.
Returns:
list: A list of merged dictionaries.
"""
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())
return output
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"]}
]
print(merge_dicts(input_dictionary))
输出:
[{'name': 'kishore', 'playing': ['cricket', 'basket ball', 'volley ball', 'hockey']}, {'name': 'xyz', 'playing': ['cricket']}]