Python ordered dictionary: Why is [] notation required to change dictionary values using a for loop?

556 Views Asked by At

I need to change the values of a Ordered Dictionary. I used a for loop but the values weren't changing. I discovered this was because I was assigning to the variable name in the loop rather than directly with the bracket [] notation. Why can't I refer to the values in the loop by the loop variable name?

Tried:

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

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

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

Full code:

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

This is probably some basic programming principle so I'm interested in 'why' so I don't make more mistakes like these. Thanks!

2

There are 2 best solutions below

0
Ignacio Vazquez-Abrams On BEST ANSWER

In the loop, name and val are bound to each of the objects in the mapping in turn. Simply rebinding the names will not modify the original iterable.

0
Marius On

Variable names in Python are references that "point to" values. Here's how that looks before you try val = idx:

enter image description here

And here's what it looks like after:

enter image description here

If you did settings['Accel X Bias'] = idx instead, you'd get:

enter image description here