Skip to content
Advertisement

How to merge two nested dictionaries in python, which have same keys and have array type values?

I need to merge two dictionaries d1 and d2, where:

d1 = {0: [array([ 42.9017, -78.6631]), array([ 41.5372, -74.0526]), array([ 39.8017, -89.6437])], 
  1: [array([ 34.7269, -86.5673]), array([ 29.7229, -98.0742])],
  2: [array([  35.9878, -115.1167]), array([  34.0316, -117.6187])],array([  61.6303, -148.9872])]}

d2 = {0: [array([5, 5], dtype=int64), array([44, 44], dtype=int64),array([1, 1], dtype=int64)], 
  1: [array([1, 1], dtype=int64), array([12, 12], dtype=int64), array([1, 1], dtype=int64)],
  2: [array([1, 1], dtype=int64), array([12, 12], dtype=int64), array([1, 1], dtype=int64)]}

I need dictionary d3 after merging d1 and d2, such that, 1st value of key:0 of d1 is merged with 1st value of key:0 of d2.

Expecting d3 as:

  d3 =  {0: [array([ 42.9017, -78.6631]), array([5, 5], dtype=int64), array([ 41.5372, -74.0526]), array([44, 44], dtype=int64) , array([ 39.8017, -89.6437]), array([1, 1], dtype=int64)], 
  1: [array([ 34.7269, -86.5673]), array([1, 1], dtype=int64), array([ 29.7229, -98.0742]), array([12, 12], dtype=int64)],
  2: [array([  35.9878, -115.1167]),array([1, 1], dtype=int64),array([1, 1], dtype=int64), array([12, 12], dtype=int64), array([  34.0316, -117.6187])],array([1, 1], dtype=int64), array([ 61.6303, -148.9872])]}

I have tried multiple approaches, but nothing seems to work appropriately. Any help is much appreciated! Thanks!

Advertisement

Answer

I hope I’ve understood your question well. You can use itertools.zip_longest to alternate between the values from the two dictionaries:

from itertools import zip_longest

out = {}
for k in d1.keys() | d2.keys():
    for v1, v2 in zip_longest(d1.get(k, []), d2.get(k, [])):
        out.setdefault(k, [])
        if not v1 is None:
            out[k].append(v1)
        if not v2 is None:
            out[k].append(v2)

print(out)

Prints:

{
    0: [
        array([42.9017, -78.6631]),
        array([5, 5]),
        array([41.5372, -74.0526]),
        array([44, 44]),
        array([39.8017, -89.6437]),
        array([1, 1]),
    ],
    1: [
        array([34.7269, -86.5673]),
        array([1, 1]),
        array([29.7229, -98.0742]),
        array([12, 12]),
        array([1, 1]),
    ],
    2: [
        array([35.9878, -115.1167]),
        array([1, 1]),
        array([34.0316, -117.6187]),
        array([12, 12]),
        array([61.6303, -148.9872]),
        array([1, 1]),
    ],
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement