尝试键入嵌套字典,但结果显示嵌套值与最后一个条目。我猜这是因为我要添加的嵌套键对于所有对象都是相同的:
for i in range(15, 19, 1):
left_index = counters[i].find(']')
right_index = counters[i].rfind(': ')
key = counters[i][left_index + 1:right_index]
value = counters[i][right_index + 1:].replace('[(','').replace(')]','').replace(') - (',' ').strip().split(' ')
d1['value'] = value[0]
d1['minimum'] = value[1]
d1['maximum'] = value[-1]
print 'key: ',key, 'value: ', d1
d[key] = d1
encoder.FLOAT_REPR = lambda x: format(x, '.5f')
print json.dumps(d, indent=5, sort_keys=True)
结果是:
key: Socket/Modem 1/Bytes sent value: {'minimum': '0', 'maximum': '2482262614', 'value': '2482262614'}
key: Socket/Modem 1/recv value: {'minimum': '0', 'maximum': '19646', 'value': '19646'}
key: Socket/Modem 1/send value: {'minimum': '0', 'maximum': '2078818', 'value': '2078818'}
key: StreamerEngine/Bonding/Priority queue/Packets of '' priority dequeued value: {'minimum': '0', 'maximum': '0', 'value': '0'}
{
" Socket/Modem 1/Bytes sent": {
"maximum": "0",
"minimum": "0",
"value": "0"
},
" Socket/Modem 1/recv": {
"maximum": "0",
"minimum": "0",
"value": "0"
},
" Socket/Modem 1/send": {
"maximum": "0",
"minimum": "0",
"value": "0"
},
" StreamerEngine/Bonding/Priority queue/Packets of '' priority dequeued": {
"maximum": "0",
"minimum": "0",
"value": "0"
}
}
因此您可以看到d1
字典的键入正确,但累积的字典d
的键入却不正确。
答案 0 :(得分:0)
d1
被(可能)在循环之外声明,所以您一次又一次使用相同对象,这就是为什么所有其他字典都使用最后一个赋值的原因。 / p>
请在循环中定义d1
:
for i in range(15, 19, 1):
left_index = counters[i].find(']')
right_index = counters[i].rfind(': ')
key = counters[i][left_index + 1:right_index]
value = counters[i][right_index + 1:].replace('[(','').replace(')]','').replace(') - (',' ').strip().split(' ')
d1 = {} # <- new dict!
d1['value'] = value[0]
d1['minimum'] = value[1]
d1['maximum'] = value[-1]
print 'key: ',key, 'value: ', d1
d[key] = d1