Combine two dictionary...

Tim Chase python.list at tim.thechases.com
Mon Oct 1 13:41:19 EDT 2007


> 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.

If you combine your dict1 and dict2 to become result_dict, what 
should the result of result_dict[3] be?  3 or 5?

It sounds like the .update() method on a dict.

You can do something like

  dict2.update(dict1)

or

  disc1.update(dict2)

depending on your answer to the above question about what 
result_dict[3] should be.

If you need to preserve dict1 and dict2, rather than update one 
of them, you can make a copy first:

  result_dict = dict(dict1)
  result_dict.update(dict2)

this will produce result_dict[3] = 3  whereas if you want it to 
return 5, swap the order of dict1 and dict.

-tkc









More information about the Python-list mailing list