Combine two dictionary...

Ian Clark iclark at mail.ewu.edu
Mon Oct 1 14:38:49 EDT 2007


Abandoned wrote:
> On 1 Ekim, 20:41, Carsten Haese <cars... at uniqsys.com> wrote:
>> On Mon, 2007-10-01 at 10:24 -0700, Abandoned wrote:
>>> Hi..
>>> dict1={1: 4,  3: 5}... and 2 millions element
>>> dict2={3: 3,  8: 6}... and 3 millions element
>>> I want to combine dict1 and dict2 and i don't want to use FOR because
>>> i need to performance.
>> You'll have to be a bit more precise here about how and where you want
>> to "combine". Should the result be a new dictionary or should it replace
>> one of dict1 or dict2? You're also not saying how you want conflicts
>> between dict1 and dict2 should be resolved. For example, both dict1 and
>> dict2 say something about the key 3. One says 5, the other says 3.
>> Should the combined dict say 3 or 5 or (3,5) or maybe even 4?
>>
>> Also, based on your earlier posts from today, I'm wondering if those
>> dicts come from executing SQL queries. If so, you might want to consider
>> combining the results in SQL (using a UNION query) instead of combining
>> them in Python.
>>
>> --
>> Carsten Haesehttp://informixdb.sourceforge.net
> 
> I want to total score..
> For example
>>> dict1={1: 4,  3: 5}... and 2 millions element
>>> dict2={3: 3,  8: 6}... and 3 millions element
> 
> result should be dict3={1:4, 3:8, 8:6}

Well not sure how this will work with 5+ million elements, but here's 
one stab at it:

     >>> dict1={1: 4,  3: 5}
     >>> dict2={3: 3,  8: 6}
     >>> for key in set(dict1.keys() + dict2.keys()):
     ...     x = dict1.get(key, 0)
     ...     y = dict2.get(key, 0)
     ...     dict3[key] = x + y
     ...
     >>> dict3
     {8: 6, 1: 4, 3: 8}

As Carsten Haese pointed out this should really be done in SQL. You 
might try something along these lines:

SELECT
   t1.id AS id,
   NVL(t1.count, 0) + NVL(t2.count, 0) AS count
FROM DUAL
LEFT JOIN (
   SELECT
     id,
     count
   FROM table1
) AS t1 ON 1=1
LEFT JOIN (
   SELECT
     id,
     count
   FROM table2
) AS t2 ON t1.id = t2.id

NOTE: I've never actually used a UNION, but you might want to look into it.

Ian





More information about the Python-list mailing list