[英]Appending values to a dict in a dictionary python
我有一本字典如下:
test_dict = {
'A': {'Total': 0, '0-20': 0, '20-40': 0,'40-60': 0,'60-80': 0,'80-100': 0},
'B': {'Total': 0, '0-20': 0, '20-40': 0,'40-60': 0,'60-80': 0,'80-100': 0}
}
我有一个元组列表,如下所示:
values = [(25.43246432903626, 4),
(31.90641345733643, 4),
(55.4526475309197, 4),
(84.13675556557858, 4),
(25.026203812005424, 4),
(34.46739945421961, 4),
(60.26098508606957, 4),
(26.270296485819014, 4),
(33.40999326977421, 4),
(61.37002681032798, 4)]
我想要做的是遍历这个值列表和 append 字典如下:遍历值列表和: -
value[idx][1]
为 4,则更新 test_dict 中 'A' dict 的值value[idx][1]
为 6,则更新 test_dict 中 'B' dict 的值为此,我编写了一个 function,名为:
编辑:
def update_objects_new(idx, test_dict, obj):
if 0 < idx < 20:
test_dict[obj]['0-20'] += 1
if 20 < idx < 40:
test_dict[obj]['20-40'] += 1
if 40 < idx < 60:
test_dict[obj]['40-60'] += 1
if 60 < idx < 80:
test_dict[obj]['60-80'] += 1
if 80 < idx < 100:
test_dict[obj]['80-100'] += 1
return test_dict
我尝试了多种方法,但是即使value[idx][1]
没有 6,test_dict 中的两个字典都会更新。所以我尝试了以下方法:
for idx in values:
if idx[1] == 4:
update_objects_new(idx[0], test_dict, 'A')
elif idx[1] == 6:
update_objects_new(idx[0], test_dict, 'B')
然而,结果并不是我所期待的。 在这里,因为值列表中没有任何 6,所以test_dict['B']
中键的值应该保持为 0,但它们也正在更新。
预期 Output:
test_dict = {
'A': {'Total': 0, '0-20': 0, '20-40': 6,'40-60': 1,'60-80': 2,'80-100': 1},
'B': {'Total': 0, '0-20': 0, '20-40': 0,'40-60': 0,'60-80': 0,'80-100': 0}
}
有什么建议么?
谢谢你。
您可以创建一个像下面这样的字典来查找字典中的键
dict_idx = dict(zip(range(5), ('0-20', '20-40', '40-60', '60-80', '80-100')))
然后使用 for 循环更新值
for a, b in values:
if b == 4:
test_dict['A'][dict_idx[int(a/20)]] += 1
if b == 6:
test_dict['B'][dict_idx[int(a/20)]] += 1
print(test_dict)
Output:
{'A': {'Total': 0, '0-20': 0, '20-40': 6, '40-60': 1, '60-80': 2, '80-100': 1},
'B': {'Total': 0, '0-20': 0, '20-40': 0, '40-60': 0, '60-80': 0, '80-100': 0}}
尽管 deadshot 的代码更简洁,但我只是将您的代码复制粘贴到 IDLE windows 中,它就可以工作。 对于您描述的问题,我能想象的唯一原因是这两个子字典实际上是相同的 object - 可能是您在 function 中创建了它们,并以空字典作为参数?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.