有以下 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']}
![]() | 1 maichael 2019-05-07 10:20:04 +08:00 ![]() 把四个字典放在一个数组里,一次遍历判断就搞定了。 |
![]() | 2 j0hnj 2019-05-07 10:25:30 +08:00 ![]() 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()} |
3 huangmiao233 OP 明白了 !!多谢 2 位 |
4 cassidyhere 2019-05-07 10:28:03 +08:00 ![]() 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]) |
5 huangmiao233 OP python 还是有很多模块能用的 还是太年轻 |
6 xpresslink 2019-05-07 22:34:56 +08:00 @helijia21 根本用不着模块啊,就一句的事儿。 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']} |