在写一些页面数据汇总的时候碰到了这样一个需求:生成了很多的字典
如:
dict1={'a':'3 host disabled','b':'0 Pending','c':'12 OK','d':''}
dict2={'b':'1 Pending','d':'4 service disabled','g':'hosts'}
dict3={'a':'1 host disabled','e':'2 DOWN','f':'services'}
...
类似这样的 每一个dict不一定所有的key都在 也有可能key在但value为空 但需要把所有dic的value进行相加汇总 输出dict 如:dict={'a':'4 host disabled','b':'1 pending','c':'12 OK','d':'4 service disabled','e':'2 DOWN'} 而且还会存在只有字母没有数字的情况 有数字的才进行相加
现在麻烦的就是 从value值中抽取数字进行相加 并且还要附加上后面的字符串 当然同一个key value涉及到的字符串是一样的。
PS:不改变原来的dict 都需要继续使用 新生成一个
有没有好的解决方案。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
其实 @yanyaoer 已经把问题解释的比较清楚了。只是 @Ajian 需要对数据做一个预处理。看在同事的份上,我帮你把 code 写出来吧~
#! /usr/bin/python # -*- coding: utf-8 -*- import string dict1={'a':'3 host disabled','b':'0 Pending','c':'12 OK','d':''} dict2={'b':'1 Pending','d':'4 service disabled','g':'hosts'} dict3={'a':'1 host disabled','e':'2 DOWN','f':'services'} statusMap = {} dataList = [] for dict in [dict1, dict2, dict3]: data = {} for k,v in dict: if len(v) <=0: continue arr = v.split(" ", 1) if (len(arr) <= 1): statusMap[k] = arr[0] continue data[k] = arr[0] statusMap[k] = arr[1] dataList.append(data) data = merge(dataList) ret = {} for k,v in ret: ret[k] = v + " " + statusMap[k] print ret#! /usr/bin/python # -*- coding: utf-8 -*- d1 = {'a':'1', 'b':'2', 'c':None} d2 = {'a':'1', 'b':'1'} d3 = {'a':'1', 'b':'3', 'c':5} def merge(dicts): ret = {} for dict in dicts: for key in dict: val = str(dict[key]) # 这里我直接连字符串了, 自己改成加操作吧 ret[key] = ret[key]+val if key in ret else val return ret print merge([d1,d2,d3]) print d1,d2,d3