Python中的Netsed字典

Python中的Netsed字典,python,dictionary,Python,Dictionary,尝试键入嵌套字典,但结果显示最后一个条目的嵌套值。我想这是因为我正在尝试添加嵌套键,该键对所有对象都是相同的: 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

尝试键入嵌套字典,但结果显示最后一个条目的嵌套值。我想这是因为我正在尝试添加嵌套键,该键对所有对象都是相同的:

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
没有。

d1
是(可能)在循环之外声明的,因此您一次又一次地使用同一对象,这就是为什么在所有其他字典中使用最后分配的值

而是在循环中定义
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
适用于范围(15,19,1)内的i:
左索引=计数器[i]。查找(']'))
右索引=计数器[i].rfind(“:”)
key=计数器[i][left\u index+1:right\u index]
value=counters[i][right_index+1:][.replace('[(',''))]',''.replace(')-(','').strip().split('')
d1={}#可能重复的