updating dictionaries from/to dictionaries

John Machin sjmachin at lexicon.net
Mon Aug 11 19:05:45 EDT 2008


On Aug 12, 2:52 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Mon, 11 Aug 2008 00:27:46 -0700, Brandon wrote:
> > This should be pretty simple:  I have two dictionaries, foo and bar. I
> > am certain that all keys in bar belong to foo as well, but I also know
> > that not all keys in foo exist in bar.  All the keys in both foo and bar
> > are tuples (in the bigram form ('word1', 'word2)).  I have to prime foo
> > so that each key has a value of 1.
>
[snip]
> > The values for the keys in bar are
> > variable integers.  All I want to do is run a loop through foo, match
> > any of its keys that also exist in bar, and add those key's values in
> > bar to the preexisting value of 1 for the corresponding key in foo.  So
> > in the end the key,value pairs in foo won't necessarily be, for example,
> > 'tuple1: 1', but also 'tuple2: 31' if tuple2 had a value of 30 in bar.
>
> Harder to say what you want to do than to just do it.
>
> The long way:
>
> for key in foo:
>     if bar.has_key(key):

dict.has_key(key) is nigh on obsolete since Python 2.2 introduced the
"key in dict" syntax.

>         foo[key] = foo[key] + bar[key]

and foo[key] += bar[key] works in Python 2.1, maybe earlier.

>
> Probably a better way:
>
> for key, value in foo.iteritems():
>     foo[key] = value + bar.get(key, 0)

Yeah, probably better than using has_key ...

>
> You should also investigate the update method of dictionaries. From an
> interactive session, type:
>
> help({}.update)
>
> then the Enter key.

I'm not sure what relevance dict.update has to the OP's problem.

Help is fine for when you need a reminder of the syntax of some method
you already know about. I'd suggest reading the manual of a modern
version of Python (http://docs.python.org/lib/typesmapping.html) to
get an overview of all the dict methods. The manual includes useful
information that isn't in help, like "a.has_key(k)  	Equivalent to k
in a, use that form in new code".



More information about the Python-list mailing list