首页 > 解决方案 > 在另一个字典中迭代和附加字典值

问题描述

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)

单独的值打印得很好,但是最终的打印键正确地作为 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}}

我想念的东西不知何故我无法思考/弄清楚。欢迎快速提示

标签: python

解决方案


您的程序几乎是正确的,只需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}}

推荐阅读