Digital addition solution in value dic

149 3

There's a requirement when writing a summary of page data: A lot of dictionaries are generated
For example:
Dict1 = % 7b 'a ': 3 % disabled ', ''% ': '0 pending ', 'c ': 12 ok ', 'd '
Dict2 = % 7b 's '1 pending ', 'd ': '4 service disabled ', 'g '': 'hosts '% referrals
Dict3 = % 7b 'a ': 1 host disabled ', '''% ': ''% ': 'f ''services '% prematurely.
...

Each dict doesn't have to have any key in it. It's also possible to add a number to value, but there's no need to add all value to, such as %, 7b. 1. %.............
Now the trouble is to extract the numbers from the value value and attach the strings that are later on, of course the same key value is the same string.

Ps: don't change the original pk to continue using new generation

There's a good solution.

2 Answers

100 0

Actually, @ yanyaoer has the problem. Just @ ajian needs to data. Look at the copy of your colleagues, I'll help you write the 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
79 4
#!/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
...