updating dictionaries from/to dictionaries

John Machin sjmachin at lexicon.net
Mon Aug 11 20:12:08 EDT 2008


On Aug 12, 9:14 am, Brandon <your.mas... at gmail.com> wrote:
> I wasn't sure about the update method either, since AFAICT (not far)
> the values would in fact update, not append as I needed them to.

"append"? Don't you mean "add"???

> But
> the iteritems and get combo definitely worked for me.

Under some definition of "worked", yes, it would. What were your
selection criteria?

>
> Thank you for the suggested link.  I'm familiar with that page, but my
> skill level isn't so far along yet that I can more or less intuitively
> see how to combine methods, particularly in dictionaries.  What would
> be a dream for me is if somebody just had tons of use-case examples -
> basically this post, condensed, for every potent combination of
> dictionary methods.  A guy can dream.

Nobody is going to write that, and if they did, what would you do?
Read it linearly, trying to find a match to your use-case? Forget
dreams. What you need to do is practice translating from your
requirements into Python, and it's not all that hard:

"run a loop through foo" -> for key in foo:
"match any of its keys that also exist in bar" -> if key in bar:
"add those key's values in bar to the preexisting value for the
corresponding key in foo" -> foo[key] += bar[key]

But you also need to examine your requirements:
(1) on a mechanical level, as I tried to point out in my first
response, if as you say all keys in bar are also in foo, you can
iterate over bar instead of and faster than iterating over foo.
(2) at a higher level, it looks like bar contains a key for every
possible bigram, and you are tallying actual counts in bar, and what
you want out for any bigram is (1 + number_of_occurrences) i.e.
Laplace adjustment. Are you sure you really need to do this two-dict
caper? Consider using only one dictionary (zot):

Initialise:
zot = {}

To tally:
if key in zot:
   zot[key] += 1
else:
   zot[key] = 1

Adjusted count (irrespective of whether bigram exists or not):
zot.get(key, 0) + 1

This method uses space proportional to the number of bigrams that
actually exist. You might also consider collections.defaultdict, but
such a dict may end up containing entries for keys that you ask about
(depending on how you ask), not just ones that exist.

HTH,
John



More information about the Python-list mailing list