在另一个字典中迭代和附加字典值

时间:2020-10-12 19:55:52

标签: python

disks={'1':1,'2':2,'3':3,'4':4,'5':5}
mem={'1':11,'2':12,'3':13,'4':14,'5':15}
cpu={'1':21,'2':22,'3':23,'4':24,'5':25}
Stats={}
Values={}
for i in range(1,len(disks)+1):
    Index="value"+str(i)
    total = disks['%s'%i]
    memory =  mem['%s'%i]
    cpus= cpu['%s'%i]
    Values["cpu"]=cpus
    Values["total"]=total
    Values["memory"]=memory

       
    print(Index) # shows right value
    print(Values) # shows right value
    Stats[Index]=Values
    print(Stats)
       
       
print (Stats)

可以很好地打印单个值,但是最终的discipananary打印键可以正确地设置为value1,value2,但是这些值都是最后一个值,正如我们在此处看到的那样:

value1
{'cpu': 21, 'total': 1, 'memory': 11}
{'value1': {'cpu': 21, 'total': 1, 'memory': 11}}
value2
{'cpu': 22, 'total': 2, 'memory': 12}
{'value1': {'cpu': 22, 'total': 2, 'memory': 12}, 'value2': {'cpu': 22, 'total': 2, 'memory': 12}}
value3
{'cpu': 23, 'total': 3, 'memory': 13}
{'value1': {'cpu': 23, 'total': 3, 'memory': 13}, 'value2': {'cpu': 23, 'total': 3, 'memory': 13}, 'value3': {'cpu': 23, 'total': 3, 'memory': 13}}
value4
{'cpu': 24, 'total': 4, 'memory': 14}
{'value1': {'cpu': 24, 'total': 4, 'memory': 14}, 'value2': {'cpu': 24, 'total': 4, 'memory': 14}, 'value3': {'cpu': 24, 'total': 4, 'memory': 14}, 'value4': {'cpu': 24, 'total': 4, 'memory': 14}}
value5
{'cpu': 25, 'total': 5, 'memory': 15}
{'value1': {'cpu': 25, 'total': 5, 'memory': 15}, 'value2': {'cpu': 25, 'total': 5, 'memory': 15}, 'value3': {'cpu': 25, 'total': 5, 'memory': 15}, 'value4': {'cpu': 25, 'total': 5, 'memory': 15}, 'value5': {'cpu': 25, 'total': 5, 'memory': 15}}

FINAL value: 
{'value1': {'cpu': 25, 'total': 5, 'memory': 15}, 'value2': {'cpu': 25, 'total': 5, 'memory': 15}, 'value3': {'cpu': 25, 'total': 5, 'memory': 15}, 'value4': {'cpu': 25, 'total': 5, 'memory': 15}, 'value5': {'cpu': 25, 'total': 5, 'memory': 15}}

我错过了某些东西,我无法以某种方式想出/找到答案。欢迎快速提示

1 个答案:

答案 0 :(得分:1)

您的程序几乎是正确的,只需将Values={}移入for循环(以创建新词典而不使用旧词典):

disks={'1':1,'2':2,'3':3,'4':4,'5':5}
mem={'1':11,'2':12,'3':13,'4':14,'5':15}
cpu={'1':21,'2':22,'3':23,'4':24,'5':25}
Stats={}
for i in range(1,len(disks)+1):
    Values={}                    # <-- move Values here
    Index="value"+str(i)
    total = disks['%s'%i]
    memory =  mem['%s'%i]
    cpus= cpu['%s'%i]
    Values["cpu"]=cpus
    Values["total"]=total
    Values["memory"]=memory

       
    # print(Index) # shows right value
    # print(Values) # shows right value
    Stats[Index]=Values
    # print(Stats)
       
       
print (Stats)

打印:

{'value1': {'cpu': 21, 'total': 1, 'memory': 11}, 'value2': {'cpu': 22, 'total': 2, 'memory': 12}, 'value3': {'cpu': 23, 'total': 3, 'memory': 13}, 'value4': {'cpu': 24, 'total': 4, 'memory': 14}, 'value5': {'cpu': 25, 'total': 5, 'memory': 15}}