Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Python
updating dictionaries from/to dictionaries
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="John Machin, post: 3609981"] "append"? Don't you mean "add"??? Under some definition of "worked", yes, it would. What were your selection criteria? 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 [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Python
updating dictionaries from/to dictionaries
Top