carmo
carmo

Reputation: 37

Change value in dictionary of dictionary

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

Upvotes: 2

Views: 787

Answers (3)

tverrbjelke
tverrbjelke

Reputation: 1294

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}}}

Upvotes: 0

Artyer
Artyer

Reputation: 40791

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

Upvotes: 1

James
James

Reputation: 36598

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

Upvotes: 5

Related Questions