Python有序字典: Why is [] notation required to change dictionary values using a for loop?

标签 python ordereddictionary

我需要更改有序字典的值。我使用了 for 循环,但值没有改变。我发现这是因为我在循环中分配给变量名,而不是直接使用方括号 [] 表示法。为什么我不能通过循环变量名来引用循环中的值?

尝试过:

idx = 0
for name,val in settings.items():
    idx += 1
    val = idx
    print name,val

结果:OrderedDict([('Accel X Bias', None), ('Mag X Bias', None)])

预期:OrderedDict([('Accel X Bias', 1), ('Mag X Bias', 2)])

完整代码:

import collections
settings = collections.OrderedDict([('Accel X Bias', None), ('Mag X Bias', None)])
idx = 0

print "\nIn loop, values are changed:"
for name,val in settings.items():
    idx += 1
    val = idx
    print name,val

print "\nAfter Loop, values didn't change:\n",settings

for name,val in settings.items():
    idx += 1
    val = idx
    settings[name] = idx
print "\nAfter Loop, bracket notation used, values changed successfully:\n",settings

这可能是一些基本的编程原则,所以我对“为什么”很感兴趣,所以我不会犯更多这样的错误。谢谢!

最佳答案

Python 中的变量名是“指向”值的引用。下面是您尝试 val = idx 之前的样子:

enter image description here

这是它之后的样子:

enter image description here

如果你改为 settings['Accel X Bias'] = idx,你会得到:

enter image description here

关于Python有序字典: Why is [] notation required to change dictionary values using a for loop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18525188/

相关文章:

python OrderedDict 获取关键索引的

python - 在 python 中重新格式化字典输出

python - 用随机数替换 NaN

python - 如何使用 Selenium 打印页面源代码

json - python json中的ordered_dict

python - 将语料库词典排序为 OrderedDict 的最快方法 - python

Python:基于键值长度的OrderedDictionary排序

python - 加快 Pandas 中的滚动窗口

python - 嵌套正则表达式

python - 无法安装软件包(通过 Powershell 在 venv 中)