def combine(d1, d2):
     for key in d1:
         if key in d2:
             d2[key] += d1[key]

[Remark]
I usually avoid changing function arguments. But later on you're talking about using this function as a method a class, so d1 and d2 would be instance attributes I guess.


When I initialize the class which holds these dictionaries, though, I need
to make sure that all the keys contained in d2 match the keys of d1. Thus I
tried:
d1 = {'a': 0, 'b': 0, 'c': 0}

Now d1 holds the address of a dict in memory. The dict contains your data.

d2 = d1

Now d2 holds the same address of the same dict in memory. d1 and d2 refer to the same dictionary.

My understanding was that d2 looked at d1 once, grabbed its keys and values,
and went off to do its own thing.

You would need to use copy() explicitly.

import copy

d2 = copy.copy(d1) # swallow copy

# or a deep copy
# -> copies also referenced objects recursively
# usefull if you have e.g. lists as values in your dict
# and want them copied too.

d2 = copy.deepcopy(d1)


 Just as if you typed:
x = 3
y = x
x = 6
y still holds the value 3.

Python has mutable and immutable types. Str and int, for example, are immutable. Dicts and list for example are mutable. The statement x=6 binds x to a new object, because the object with value 3 cannot be changed.

There are a lot of explanations about mutable and immutable types. Much better then I could. You could search the list, for example here: http://dir.gmane.org/gmane.comp.python.tutor
or the web or see this overview in the docs:
http://docs.python.org/reference/datamodel.html#objects-values-and-types

Generally, I wouldn't copy an existing dict to make sure the other dict has the same values. The data must come from somewhere. I would check the data, then you wouldn't need to check the container.

Finally, you could use dict.get with a default set to 0, then you wouldn't need to care, e.g. (using dict comprehension and creating a new dict):

def combine_2(d1, d2):
    return {key: d1[key]+d2.get(key, 0) for key in d1}

But that's a bit dirty semantic wise, better to check the input data ... just to show you the syntax.


HTH,

Jan

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to