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)
单独的值打印得很好,但是最终的打印键正确地作为 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}}
我想念的东西不知何故我无法思考/弄清楚。欢迎快速提示
解决方案
您的程序几乎是正确的,只需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}}
推荐阅读
- java - 代理设置应该在 Maven 级别或 IDE 级别或两者兼而有之?
- gekko - GEKKO 模式 4 和 7 的结果不一致
- reactjs - 即使使用市场查询参数,Spotify API 也会提供具有相同名称但不同 ID 的专辑
- c++ - 112.path sum leetcode wong 两个测试用例的答案
- botframework - 如何在 Bot Framework V4 中使用语言生成同时处理多个活动
- python - Python:按字母顺序对列表进行排序,忽略元音
- python - 如何使用列表中 URL 中的图像以供以后在 Tkinter 中使用?
- spring-boot - 不为映射器类注入模拟数据时的 NPE(弹簧启动)
- javascript - 字符串给定值的方形数组
- flutter - 获取类型“Null”不是“Future”类型的子类型
' 在使用 mockito 的颤振单元测试中进行类型转换