papu papu - 27 days ago 12
Python Question

merging dicts in python

I am new to python..I have two sorted arrays (by key) that I would like to merge. Both arrays have some common keys and some exist uniquely in one of the arrays. I want to do an outer join.

Array1 = {'key_1': 10, 'key_2': 14,..'key_m': 321}
Array2 = {'key_1': 15, 'key_2': 12..'key_m':2,..'key_n':34}


I want to merge using key_1..key_n..

Array3 = [[key_1',10,15],['key_2':14:12],..]


I don't have numpy package installed on my computer. Do I need it to merge this array? what is the best way to code this up? Thanks!!!

Answer

How about this?

#!/usr/bin/env python
from itertools import chain

dict1 = {'key_1': 10, 'key_2': 14, 'key_m': 321}
dict2 = {'key_1': 15, 'key_2': 12, 'key_m':2, 'key_n':34}

dict3 = {}

# Go through all keys in both dictionaries
for key in set(chain(dict1, dict2)):

    # Find the key in either dictionary, using an empty
    # string as the default if it is not found.
    dict3[key] = [dict.get(key, "")
                  for dict in (dict1, dict2)]

print(dict3)

Now dict3 has a list of every value from the input arrays.

Or if you want it in that [[key, value, value], [key, value, value]...] format:

#!/usr/bin/env python
from itertools import chain

dict1 = {'key_1': 10, 'key_2': 14, 'key_m': 321}
dict2 = {'key_1': 15, 'key_2': 12, 'key_m':2, 'key_n':34}

result = [[key] + [dict.get(key, "")
           for dict in (dict1, dict2)]
          for key in set(chain(dict1, dict2))]
result.sort()

print(result)
Comments