Python中字典合并问题请教

有以下 4 个字典

dict1={'status':'on', 'location':'a'}
dict2={'status':'on', 'location':'b'}
dict3={'status':'off', 'location':'c'}
dict4={'status':'off', 'location':'d'}

有没有什么办法快速得到

result = {'on':['a','b'], 'off':['c','d']}

Python中字典合并问题请教

7 回复

把四个字典放在一个数组里,一次遍历判断就搞定了。


在Python中合并字典,有几种主流方法,各有适用场景。

1. 使用 update() 方法 (原地修改) 这是最经典的方法,它会修改原字典。dict2 的键值对会覆盖 dict1 中相同的键。

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1)  # 输出: {'a': 1, 'b': 3, 'c': 4}

2. 字典解包 ** (Python 3.5+, 创建新字典) 使用 ** 解包操作符,可以合并多个字典并创建一个新字典。后面的字典会覆盖前面字典中相同的键。

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)  # 输出: {'a': 1, 'b': 3, 'c': 4}
# dict1 和 dict2 保持不变

3. 使用 | 合并运算符 (Python 3.9+, 创建新字典) 这是Python 3.9引入的专门用于字典合并的运算符,非常直观。

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = dict1 | dict2
print(merged_dict)  # 输出: {'a': 1, 'b': 3, 'c': 4}
# 也有原地合并运算符 |=
dict1 |= dict2
print(dict1)  # 输出: {'a': 1, 'b': 3, 'c': 4}

总结建议: 根据你的Python版本和是否需要创建新字典来选择合适的合并方法。

from collections import defaultdict

result = defaultdict(set)
for d in [dict1, dict2, dict3, dict4]:
result[d[‘status’]].add(d[‘location’])
result = {k:list(v) for k,v in result.items()}

明白了 !!多谢 2 位

from operator import itemgetter
from itertools import groupby

rows = [dict1, dict2, dict3, dict4]
for status, items in groupby(rows, key=itemgetter(‘status’)):
print(status, [i[‘location’] for i in items])

python 还是有很多模块能用的 还是太年轻

根本用不着模块啊,就一句的事儿。
dict1={‘status’:‘on’, ‘location’:‘a’}
dict2={‘status’:‘on’, ‘location’:‘b’}
dict3={‘status’:‘off’, ‘location’:‘c’}
dict4={‘status’:‘off’, ‘location’:‘d’}
dicts = [dict1,dict2,dict3,dict4]
result = {}
for d in dicts: result.setdefault(d[‘status’],[]).append(d[‘location’])
print(result)
# {‘on’: [‘a’, ‘b’], ‘off’: [‘c’, ‘d’]}

回到顶部