updating dictionaries from/to dictionaries

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Aug 11 12:52:55 EDT 2008


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.

The old way:

foo = {}
for key in all_the_keys:
    foo[key] = 1


The new way:

foo = dict.fromkeys(all_the_keys, 1)


> 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):
        foo[key] = foo[key] + bar[key]



Probably a better way:

for key, value in foo.iteritems():
    foo[key] = value + bar.get(key, 0)



You should also investigate the update method of dictionaries. From an 
interactive session, type:

help({}.update)

then the Enter key.



-- 
Steven



More information about the Python-list mailing list