示例:python环境下字典和列表重组的一个小例子

#发文福利#

#!/usr/bin/env python
# -*- coding:utf-8 -*-

result = {}
iplist = ['1.1.1.1', '1.1.1.2', '1.1.1.3', '1.1.1.4', '1.1.1.5', '1.1.1.6']

for i in iplist:
    tmp1 = int(i.split(".")[3])
    jmx_state = 'online' if tmp1 % 2 == 1 else 'offline'
    address = 'shanghai' if tmp1 % 2 == 1 else 'hangzhou'
    result[i] = {'jmx_state': jmx_state, 'address': address, 'cmdb_state': '', 'compare': ''}
print result
#{'jmx_state': 'offline', 'address': 'hangzhou'}
cmdb_state = 'haha'
result['1.1.1.2']['cmdb_state'] = cmdb_state

if result['1.1.1.2']['cmdb_state'] == 'hehe':
    result['1.1.1.2'].update({'compare': 'success'})
else:
    result['1.1.1.2'].update({'compare': 'not ok'})
print result['1.1.1.2']  # {'jmx_state': 'offline', 'compare': 'not ok', 'cmdb_state': 'haha', 'address': 'hangzhou'}

for k,v in result.items():
    var1 = [k,v['jmx_state'],v['address'],v['cmdb_state'],v['compare']]
    print ','.join(var1)

调试结果如下

{'1.1.1.4': {'jmx_state': 'offline', 'compare': '', 'cmdb_state': '', 'address': 'hangzhou'}, '1.1.1.5': {'jmx_state': 'online', 'compare': '', 'cmdb_state': '', 'address': 'shanghai'}, '1.1.1.6': {'jmx_state': 'offline', 'compare': '', 'cmdb_state': '', 'address': 'hangzhou'}, '1.1.1.1': {'jmx_state': 'online', 'compare': '', 'cmdb_state': '', 'address': 'shanghai'}, '1.1.1.2': {'jmx_state': 'offline', 'compare': '', 'cmdb_state': '', 'address': 'hangzhou'}, '1.1.1.3': {'jmx_state': 'online', 'compare': '', 'cmdb_state': '', 'address': 'shanghai'}}
{'jmx_state': 'offline', 'compare': 'not ok', 'cmdb_state': 'haha', 'address': 'hangzhou'}
1.1.1.4,offline,hangzhou,,
1.1.1.5,online,shanghai,,
1.1.1.6,offline,hangzhou,,
1.1.1.1,online,shanghai,,
1.1.1.2,offline,hangzhou,haha,not ok
1.1.1.3,online,shanghai,,

听哥一句劝,不要做运维 

你可能感兴趣的:(python,服务器,python)