2

I want to change values I have stored in a dictionary of dictionaries.

This is the code I tried to implement. The problem is p remains the same, and I'm not sure how to update p.

j = {'a':1.0}
k = {'c':3.0}
p = {'e':j,'f':k}
for n in p.itervalues():
    print n
    n = {key:value/3.0 for key, value in n.items()}
    print n

print p
carmo
  • 37
  • 3

3 Answers3

6

You need to assign the updated value back to the original dictionary.

j = {'a':1.0}
k = {'c':3.0}
p = {'e':j,'f':k}
for k,v in p.items():
    p[k] = {key:value/3.0 for key, value in v.items()}

print p
James
  • 32,991
  • 4
  • 47
  • 70
1

When you do n = {...}, you are assigning a different dictionary to n.

If you want to change both p and the original dictionaries (j and k), you could do something like this:

Since dictionaries are mutable, you can replace it's content with that of another dict like this:

def replace_dict(original, new):
    original.clear()
    original.update(new)

And then do replace_dict(n, {key:value/3.0 for key, value in v.items()}).


Since all you are doing is applying a function ("divide by 3") to each value, you can also do something like this:

    for key, value in n.iteritems():
        n[key] = value / 3.0
Artyer
  • 31,034
  • 3
  • 47
  • 75
0

I think it's worth mentioning you are using python2.

#!/usr/bin/env python2
j = {'a': 1.0}
k = {'c': 3.0}
p = {'e': j, 'f': k}
for v in p.itervalues():
    print "v before inplace updates:", v
    for k, v_inside in v.items():
        print "v[k] before inplace change", v[k]
        v[k] = {key: value / 3.0 for key, value in v.items()}
        print "v[k] after inplace change", v[k]
print "p after inplace edits:\n", p

Produces this output:

v before inplace updates: {'a': 1.0}
v[k] before inplace change 1.0
v[k] after inplace change {'a': 0.3333333333333333}
v before inplace updates: {'c': 3.0}
v[k] before inplace change 3.0
v[k] after inplace change {'c': 1.0}
p after inplace edits:
{'e': {'a': {'a': 0.3333333333333333}}, 'f': {'c': {'c': 1.0}}}
tverrbjelke
  • 1,234
  • 10
  • 15
  • I now see, always someone is faster :-D still post this, just because others can immediately see the produced output – tverrbjelke Jan 05 '18 at 14:15