papu
papu

Reputation: 35

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

Upvotes: 0

Views: 3823

Answers (2)

Brendan Long
Brendan Long

Reputation: 54242

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)

Upvotes: 3

Roshan Mathews
Roshan Mathews

Reputation: 5898

Your Array3 has incorrect syntax. You can try something like this:

>>> Array1 = {'key_1': 10, 'key_2': 14, 'key_m': 321}
>>> Array2 = {'key_1': 15, 'key_2': 12, 'key_m':2, 'key_n':34}
>>>
>>> Array3_dict = dict()
>>> for Array in (Array1, Array2):
...     for key, value in Array.items():
...         if not key in Array3_dict: Array3_dict[key] = list()
...         Array3_dict[key].append(value)
...
>>> Array3 = [ [ key ] + value for key, value in Array3_dict.items() ]
>>> Array3.sort()
>>> print Array3
[['key_1', 10, 15], ['key_2', 14, 12], ['key_m', 321, 2], ['key_n', 34]]
>>>

Upvotes: 1

Related Questions